Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   pointer stuck ! (http://www.go4expert.com/forums/pointer-stuck-t23089/)

juglers 24Aug2010 12:46

pointer stuck !
please explain what is being done in the pointer conversion in the prg

struct MyStruct
int i;
int j;

int main()
struct MyStruct *p=0;

int size = ((char*)(p+1))-((char*)p); :confused:

return 0;

thank you

shankar.489 25Aug2010 11:49

Re: pointer stuck !
hey wat is need of typecasting there it is not required.
answer 4 ur program is 8, let me explain u clearly in C all type of pointer size is 4bytes(compiler dependent i considered this one under GCC) in aabove r adding increment pointer of mystruct type by 1 so it will point to next 8 bytes(same like array concept)
note: you r adding 1 to pointer before type casting it so u r getting 8
if it is like this (((char*)p)+1)-((char*)p) then answer may be as u expected and analysis of my exp is
->adding 1 to char pointer(here i typecasted it first and then added 1 in ur case it is reverse) so it will point to next byte(as i type casted this one as char* so it will point to next byte if it is int(casted one) then it should increment by 4).
->subtraction is common means base address,no need of type casting it. i just didn`t this 4 ur analazy.


shankar.489 25Aug2010 11:50

Re: pointer stuck !
correct "i just didn`t" to "i just did"

xpi0t0s 25Aug2010 12:49

Re: pointer stuck !
It's a stupid way of doing sizeof.

p is a pointer to MyStruct so p+1 (using pointer semantics) points to the next MyStruct in memory, i.e. p+sizeof(MyStruct) in byte semantics. p+1 and p are then both cast to char* because the pointer semantics work the same way: p+1 for a char* points to p+sizeof(char) which is equivalent to p+1 in byte semantics. Subtracting p from p+1 using char* pointer semantics gives you a sizeof(char) difference between p and p+1, which is equivalent to sizeof(MyStruct).

So that whole silly complex line that you can't understand - for good reason - can be replaced with the considerably easier:

int size=sizeof(struct MyStruct);
and the programmer who wrote that nonsense should be fired.

shankar.489 25Aug2010 12:53

Re: pointer stuck !
i told hims as newbie (in his lang) itself not to impress others especialy u? analyzing doesnt matters ways of expressing to others in their way matters always

All times are GMT +5.5. The time now is 04:10.