我正在使用gcc来编译我的程序:
$ gcc --version
gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
我知道有不同的C标准:
我的观点是,它们在声明静态数组方面存在差异。
在C89(C90)中你不能有这样的数组:
#include <stdio.h>
int main(int argc, char **argv)
{
int n = 4; //or const int n = 4
int tab1[n] = {1,2,3,4};
return 0;
}
但在C99中,你可以:
#include <stdio.h>
int main(int argc, char **argv)
{
int n = 4; // or const int n = 4
int tab1[n] = {1,2,3,4};
int tab2[3] = {5,6,7};
return 0;
}
但是当我使用gcc arrays_size.c -std=c99 -o arrays_size
#include <stdio.h>
int main(int argc, char **argv)
{
int n = 4; // or const int n = 4
int tab1[n] = {1,2,3,4};
return 0;
}
它给了我:
arrays_size.c: In function ‘main’:
arrays_size.c:6:5: error: variable-sized object may not be initialized
arrays_size.c:6:5: warning: excess elements in array initializer [enabled by default]
arrays_size.c:6:5: warning: (near initialization for ‘tab1’) [enabled by default]
arrays_size.c:6:5: warning: excess elements in array initializer [enabled by default]
arrays_size.c:6:5: warning: (near initialization for ‘tab1’) [enabled by default]
arrays_size.c:6:5: warning: excess elements in array initializer [enabled by default]
arrays_size.c:6:5: warning: (near initialization for ‘tab1’) [enabled by default]
arrays_size.c:6:5: warning: excess elements in array initializer [enabled by default]
arrays_size.c:6:5: warning: (near initialization for ‘tab1’) [enabled by default]
虽然应该正确,对吗?与使用gcc arrays_size.c -o arrays_size
...
我的问题:
干杯!
答案 0 :(得分:3)
当数组的大小是变量时,无法以这种方式初始化数组。这不起作用。
int tab1[n] = {1,2,3,4};
但这会:
int tab1[4] = {1,2,3,4};
gcc
接受大小为n
的字符数组不符合C89标准。 gcc
支持将其作为扩展名。
答案 1 :(得分:1)
是否有理由让 n 成为整数?如果您使用了预处理器宏(#define),它将在两种情况下都有效。
#define ARRAY_SIZE 4
int tab1[ARRAY_SIZE] = {1,2,3,4};
更安全的实施:
int tab1[] = {1,2,3,4}
int n = sizeof(tab1)/sizeof(tab1[0]);
这会以允许您修改数组的方式移动大小计算,而无需修改大小声明符。