我会得到什么,如果我声明数组没有在全球范围的大小? [英] What do I get if I declare an array without a size in global scope?

查看:174
本文介绍了我会得到什么,如果我声明数组没有在全球范围的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

答案之一的的:// codegolf.stackexchange.com/q/2203/38214\">Tips在C 打高尔夫,我看到这个code(ungolfed版):

  S [],T;主(三){
    对于(scanf函数(%* D);〜(C =的getchar()); S [T +] = C)
        的putchar(S [T]);
}

我认为上面的程序表现出UB(但谁在code高尔夫在乎呢?)。但我不明白的事情是 S [] 在全球范围内。我知道,当未指定全局变量的类型,默认为 INT 。我创建了一个小程序,它令人惊讶的编译:

 的#include<&stdio.h中GT;的int [];
INT主要(无效)
{
    的printf(你好!);
}

虽然它会发出警告:

prog.c中:23:5:警告:数组的'假设有一个元素[默认启用]
 的int [];
     ^


  • 什么是取值在上面的程序?它是一个为int * 或其他什么东西?

  • 这会不会是有用的地方?


解决方案

  

什么是取值在上面的程序?它是一个int *或别的东西吗?


取值是一个不完整的类型。这就是为什么你不能的sizeof 它。作为@BLUEPIXY所暗示的,它是零,因为它在全球范围内声明作出初步定义初始化。


  

INT I []; 结果
  数组我仍然有不完整的类型,隐含的初始化使其有一个元素,它被设置为
  零对程序启动。


现在,


  

这会不会是有用的地方?


它如果你只是使用的pretty没用 S [0] ,因为在这一点上你去为 S; 直接。但是,如果你需要有一定大小的数组,你不关心瑞银(UBS),这是还行。

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?

解决方案

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".

这篇关于我会得到什么,如果我声明数组没有在全球范围的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆