可能重複:
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中是不行的。這就是其中之一。 –