如果我在全局范围内声明一个没有大小的数组,我会得到什么?
What do I get if I declare an array without a size in global scope?
在one of the answers in Tips for golfing in C中看到这段代码(非高尔夫版本):
s[],t;
main(c){
for(scanf("%*d "); ~(c=getchar()); s[t++]=c)
putchar(s[t]);
}
我认为上面的程序展示了 UB(但谁在乎代码高尔夫?)。但是我不明白的是全局范围内的 s[]
。我知道当没有指定全局变量的类型时,它默认为int
。我创建了一个令人惊讶的编译小程序:
#include <stdio.h>
int s[];
int main(void)
{
printf("Hello!");
}
虽然它发出一个警告:
prog.c:23:5: warning: array 's' assumed to have one element [enabled by default]
int s[];
^
- 上面程序中的
s
是什么?是 int*
还是其他什么?
- 这对任何地方都有用吗?
What is s
in the above program? Is it an int* or something else?
s
是一个不完整的类型。这就是为什么你不能 sizeof
它。正如@BLUEPIXY 所建议的那样,它被初始化为零,因为它是在全局范围内声明的 "tentative definition"。
int i[];
the array i still has incomplete type, the implicit initializer causes it to have one element, which is set to
zero on program startup.
现在,
Will this be useful anywhere?
如果您只是使用 s[0]
,那将毫无用处,因为此时您会直接使用 s;
。但是,如果您需要一个具有特定大小的数组并且您不关心 UB,则它是 "okay".
在one of the answers in Tips for golfing in C中看到这段代码(非高尔夫版本):
s[],t;
main(c){
for(scanf("%*d "); ~(c=getchar()); s[t++]=c)
putchar(s[t]);
}
我认为上面的程序展示了 UB(但谁在乎代码高尔夫?)。但是我不明白的是全局范围内的 s[]
。我知道当没有指定全局变量的类型时,它默认为int
。我创建了一个令人惊讶的编译小程序:
#include <stdio.h>
int s[];
int main(void)
{
printf("Hello!");
}
虽然它发出一个警告:
prog.c:23:5: warning: array 's' assumed to have one element [enabled by default]
int s[];
^
- 上面程序中的
s
是什么?是int*
还是其他什么? - 这对任何地方都有用吗?
What is
s
in the above program? Is it an int* or something else?
s
是一个不完整的类型。这就是为什么你不能 sizeof
它。正如@BLUEPIXY 所建议的那样,它被初始化为零,因为它是在全局范围内声明的 "tentative definition"。
int i[];
the array i still has incomplete type, the implicit initializer causes it to have one element, which is set to zero on program startup.
现在,
Will this be useful anywhere?
如果您只是使用 s[0]
,那将毫无用处,因为此时您会直接使用 s;
。但是,如果您需要一个具有特定大小的数组并且您不关心 UB,则它是 "okay".