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); return 0; } thank you
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. regards shankar AMI-India
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: Code: int size=sizeof(struct MyStruct); and the programmer who wrote that nonsense should be fired.
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