I am still a beginner. Can someone explain to me why the output of this program is 9?
Code:#include<stdio.h> #include<string.h> void f(int * w) {*w = *w+sizeof(w);} main(){ int a=5; f(a); printf("%d\n", a); }
I am still a beginner. Can someone explain to me why the output of this program is 9?
Code:#include<stdio.h> #include<string.h> void f(int * w) {*w = *w+sizeof(w);} main(){ int a=5; f(a); printf("%d\n", a); }
You probably should have written:
Notice that:Code:#include<stdio.h> void f(int *w) { *w = *w + sizeof(w); } int main(void) { int a = 5; f(&a); printf("%d\n", a); }
- #include<string.h> was removed as none of the functions declared within it were used.
- The code for function f has been formatted properly.
- main has been declared as int main(void), not just as main(). You should declare the return type, and while it is optional in a function definition, you should declare the parameter list as void if the function takes no arguments.
- f(a) has been changed to f(&a). f(a) is wrong since a is an int, but f expect a pointer to int as the argument.
- I kept to the leaving out of the return statement from main as it is a special case since C99, but if you are compiling with respect to pre-C99, you should have a return 0; at the end of main.
Since &a was passed to f, w points to a, so *w is a, i.e., it has a value of 5. sizeof(w) presumably is 4 for you, so the result is 9. Note that the size of a pointer is not necessarily 4 bytes, so you could end up with a different valid result, e.g., if sizeof(w) == 8, the result would be 13.Originally Posted by SauceGod
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It seems "why is the result XYZ?" is becoming your theme, OP. Wouldn't it make sense to experiment and try to find out why these results are happening?
Just an idea. Sometimes a little inspection goes a long way.Code:#include <stdio.h> void f(int *w) { *w = *w + sizeof(w); } int main(void) { int a = 5; printf("value of a=%d\n", a); printf("value of sizeof(&a)=%d\n", (int) sizeof(&a)); f(&a); printf("result of f(&a)=%d\n", a); return 0; }
Last edited by whiteflags; 06-29-2016 at 07:02 PM.