可能重复:
Definition of global variables using a non constant initializer分配内存以静态变量只有一次
我有这样的代码:
#include <stdio.h>
#include <stdlib.h>
int foo (int num, int i)
{
static int* array = malloc(sizeof(int)); // ERROR HERE!!!
printf("%d", array[i]);
return 0;
}
int main(int argc, char *argv[])
{
int i;
for (i = 0; i < 2; i++) {
foo(i, i);
}
return 0;
}
我保存代码的C源文件,我无法工作? error prompt
:
gcc -O2 -Wall test.c -lm -o test
test.c:4:1: error: initializer element is not constant
Compilation exited abnormally with code 1 at Sat Jan 05 21:33:56
但是,我将它另存为C++源文件,它工作正常。为什么?有没有人可以向我解释?
这是因为C和C++是不同的语言。在C中有些事情是可以的,在C中是不行的。这就是其中之一。 –