可能重复:
使用非常量初始化器定义全局变量
我有这个代码:
#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;
}
我将代码保存为ac源文件,我不能工作?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++ 源文件,它工作正常。为什么?有人可以向我解释吗?