Why doesn't this run?
#include <stdio.h>
int x = 12;
int *p;
p = &x;
int main(void)
{
printf("%d\n", *p);
return 0;
}
According to K&R (http://en.wikipedia.org/wiki/The_C_Programming_Language_%28book%29) it's valid C.
Quote from: Gary Willoughby on December 15, 2009, 11:28:14 PM
Why doesn't this run?
#include <stdio.h>
int x = 12;
int *p;
p = &x;
int main(void)
{
printf("%d\n", *p);
return 0;
}
According to K&R (http://en.wikipedia.org/wiki/The_C_Programming_Language_%28book%29) it's valid C.
It doesn't work because the assignment p = &x; must be done inside a function.
Another way of seeing it is - the only code generated is inside functions.
John
Great, thanks.
Can you please explain why it needs to be in a function? Is it because you can only do initializations outside?
Quote from: Gary Willoughby on December 16, 2009, 09:21:29 AM
Great, thanks.
Can you please explain why it needs to be in a function? Is it because you can only do initializations outside?
You can create only globale datas outside a function. You use in your example a C instruction outside a function.
In your case following is also possible, because at the creation you can assign a content to a variable.
#include <stdio.h>
int x = 12; // create int with content 12
int *p = &x; // create pointer with content address of int x
int main(void)
{
printf("%d\n", *p);
return 0;
}
Quote from: Gary Willoughby on December 16, 2009, 09:21:29 AM
Great, thanks.
Can you please explain why it needs to be in a function? Is it because you can only do initializations outside?
I think Alex has answered your question.
John
Thanks alot guys :D