views:

411

answers:

3

I have tried this example of array of pointers. I am getting the error "Illegal initialisation in function main"

int main()
{
    int a[]={1,2,3,4,5};
    int b[]={1,2,3,4,5};
    int c[]={1,2,3,4,5};
    int *p[3]={a,b,c};
    int i;
    clrscr();
    for(i=0;i<3;i++)
     printf("%d - %u\n",*p[i],p[i]);
    getch();
}

If I use static int instead of int in array declarations, it works fine. Can any one tell me the effect of static here. Thanks a lot.

+3  A: 

This compiles fine with gcc and gcc -ansi. gcc -ansi -pedantic however gives the following warning:

blackjack.c: In function ‘main’:
blackjack.c:8: warning: initializer element is not computable at load time
blackjack.c:8: warning: initializer element is not computable at load time
blackjack.c:8: warning: initializer element is not computable at load time

Whereas line 8 is:

int *p[3]={a,b,c};

As I see it the problem is that at the time a, b, and c would be stored in p, they don't exist yet. That's because they will be put on the stack and the position on the stack depends on things outside the scope of a function. To clarify this, 'load time' means the time the program is loaded into memory, not the time it is already in execution. (Don't ask me why/how it works anyway)

ypnos
+5  A: 

In gcc you see warnings about this if you use the -pedantic flag.

But this is apparently something that has changed in the standard, in C90 it say:

All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions

and it was not allowed as the p array is an aggregate type, but in C99 we have:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

Zitrax
The rule you cite doesn't apply here. p doesn't have static storage duration.
bendin
True it seems like it has changed, I updated my answer.
Zitrax
A: 

try: printf("%d - %u\n",*(p[i]),p[i]);

although I have a feeling you're trying to do something more like:

int a[]={1,2,3,4,5};
int b[]={1,2,3,4,5};
int c[]={1,2,3,4,5};
int *p[3]={a,b,c};
int i;
clrscr();
for(i=0;i<sizeof(p)/sizeof(int*);i++) {
 for (int j =0; j < sizeof(a)/sizeof(int); j++) {
  printf("%d - %u\n",(p[i])[j],p[i]);
 }
}
getch();