What do I get if I declare an array without a size in global scope?

感情迁移 提交于 2020-01-03 15:15:13

问题


In one of the answers in Tips for golfing in C, I saw this code (ungolfed version):

s[],t;

main(c){
    for(scanf("%*d "); ~(c=getchar()); s[t++]=c)
        putchar(s[t]);
}

I think that the above program exhibits UB (but who cares in code golf?). But the thing that I don't understand is the s[] in global scope. I know that when the type of a global variable isn't specified, it defaults to int. I created a small program which surprisingly compiles:

#include <stdio.h>

int s[];
int main(void)
{
    printf("Hello!");
}

though it emits one warning:

prog.c:23:5: warning: array 's' assumed to have one element [enabled by default]
 int s[];
     ^
  • What is s in the above program? Is it an int* or something else?
  • Will this be useful anywhere?

回答1:


What is s in the above program? Is it an int* or something else?

s is an incomplete type. That's why you cannot sizeof it. As @BLUEPIXY suggests, it's initialized with zero because it's declared in global scope making a "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.

Now,

Will this be useful anywhere?

It's pretty useless if you're just using s[0] because at that point you go for s; directly. But, if you need an array with a certain size and you don't care about UBs, it's "okay".



来源:https://stackoverflow.com/questions/30424495/what-do-i-get-if-i-declare-an-array-without-a-size-in-global-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!