NO

Author Topic: Simple pointer question  (Read 3605 times)

Gary Willoughby

  • Guest
Simple pointer question
« on: December 15, 2009, 11:28:14 PM »
Why doesn't this run?
Code: [Select]
#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

  • Guest
Re: Simple pointer question
« Reply #1 on: December 16, 2009, 08:38:29 AM »
Why doesn't this run?
Code: [Select]
#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
« Last Edit: December 16, 2009, 08:48:46 AM by JohnF »

Gary Willoughby

  • Guest
Re: Simple pointer question
« Reply #2 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?

Offline AlexN

  • Global Moderator
  • Member
  • *****
  • Posts: 394
    • Alex's Link Sammlung
Re: Simple pointer question
« Reply #3 on: December 16, 2009, 09:56:44 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.
 
Code: [Select]
#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

  • Guest
Re: Simple pointer question
« Reply #4 on: December 16, 2009, 10:04:53 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

  • Guest
Re: Simple pointer question
« Reply #5 on: December 16, 2009, 03:35:41 PM »
Thanks alot guys :D