the output:Code:#include <stdio.h> void func(int a, int b) { int * p; p = &b ; p -= 2 ; (*p)+= 10; } main() { int num; num = 0; func(1,2); num = 12; printf(" Num is now %d \n",num); }
Code:Num is now 0
why num is 0??
It must be 12.. I guess
the output:Code:#include <stdio.h> void func(int a, int b) { int * p; p = &b ; p -= 2 ; (*p)+= 10; } main() { int num; num = 0; func(1,2); num = 12; printf(" Num is now %d \n",num); }
Code:Num is now 0
why num is 0??
It must be 12.. I guess
Eh, that program results in undefined behaviour, methinks. You made p point to b in func(), but then reduced p by 2. This means that p no longer points to b, so your (*p)+= 10; line changes something other than b.
You probably wanted to write:
With this revised program, I get the output you expected.Code:#include <stdio.h> void func(int a, int b) { int * p; p = &b; *p -= 2; *p += 10; } int main() { int num; num = 0; func(1, 2); num = 12; printf(" Num is now %d \n", num); return 0; }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Changing the value that is 2 integer sizes before b in the memory is pretty undefined - that could be ANYTHING. Someone who wrote this code obviously meant for it to modify the "num" value, but there's no guarantee whatsoever that there isn't "stuff" between num and b that is there because the compiler decided to put other stuff there.... Such as the program counter, frame pointer, locally stored registers, etc, etc.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.