Thursday, July 30, 2009

Why should i use int pointer to store integer value in c?

Let me tell you what happens if you don't.





Say you are on a machine where an int is 32 bits(4bytes). And a short is 16 bits(2 bytes) and you do this.





int y = 10;


short *z = (short *)%26amp;y;


*z = 12;





Well the location that is storing the y has 4 bytes, but because you are using z a short (2 bytes) pointer it transfers only 2 bytes. In other words the type of pointer decides how many bytes to copy, not the location (y). This also affects things like z++ moves to the memory location two bytes higher, where as if z had been a integer pointer it would have moved it by 4 bytes.





By the way I used (short *) above, because if I didn't the compiler would complain that I'm trying to do this most likely bad thing. There are cases where a programer might actually want to only transfer only two bytes so C lets you tell the compiler to accept this, with this syntax, which is a cast, as in cast (change) the integer pointer into a short pointer.


No comments:

Post a Comment