Simple pointer question

Started by Gary Willoughby, December 15, 2009, 11:28:14 PM

Previous topic - Next topic

Gary Willoughby

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 it's valid C.

JohnF

#1
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 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

Gary Willoughby

Great, thanks.

Can you please explain why it needs to be in a function? Is it because you can only do initializations outside?

AlexN

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;
}
best regards
Alex ;)

JohnF

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

Gary Willoughby