3

我试过这个指针数组的例子。我收到错误“函数 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();
}

如果我在数组声明中使用 static int 而不是 int ,它可以正常工作。谁能告诉我这里的静态效果。非常感谢。

4

4 回答 4

5

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.

于 2009-02-14T18:53:27.490 回答
4

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)

于 2009-02-14T18:52:17.803 回答
0

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();
于 2009-02-14T19:15:48.293 回答
0

规则非常简单。对于静态对象,初始化列表应该是常量。对于将在堆栈上分配空间的元素不存在这样的限制。这看起来也很合乎逻辑,因为静态对象需要写入数据部分,并且编译器必须能够事先解析它们的值。一旦调用了有问题的函数(main),就会在堆栈上分配内存。所以没有问题。我不知道为什么turbo-c上的行为相反。在 gcc 上会发生这种情况:(在使用gcc -Wall prog.c编译时

        int *p[]={a,b,c} //works fine
        static int *p[]={a,b,c} //oops blunder
于 2011-11-25T02:40:28.543 回答