c - 无维度的全局整数数组

标签 c arrays global

我们定义一个没有维度的全局数组是什么概念 这显示输出为 16。

    #include <stdio.h>
    #include <stdlib.h>
    int arr[];

    int main(int argc, char *argv[])
    {
        arr[1] = 16;

      printf("%d\n",arr[1]);
      system("PAUSE");  
      return 0;
    }

甚至 sizeof(arr) 也不起作用。为什么?

最佳答案

int arr[]; 是那里的一个暂定定义

条款 6.9.2,第 2 段说:

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

该条款第 5 段中的示例 2 阐明:

If at the end of the translation unit containing

   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.

因此在翻译单元的末尾,您的数组arr 的类型为int[1]。在结束之前,它的类型不完整,因此 sizeof 不起作用,因为在 main 中,数组类型仍然不完整。

访问 arr[1] 会调用未定义的行为,因为 arr 只有一个元素。

关于c - 无维度的全局整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242690/

相关文章:

代码编译等,但只是卡在运行

Python-将全局变量分配给函数返回需要函数是全局的吗?

c - 如何在 if 语句中初始化一个变量并在 if 语句之外使用它

c - 将新值插入C中的堆栈中

c - C 中的多线程 : passing a structure

c - 如果重复使用 atoi 函数会遇到问题

arrays - 我可以在 Perl 中命名一个匿名数组吗?

c# - 如何在 C# 中创建一维动态数组?

javascript - 未捕获的类型错误 : Cannot set property 'background' of undefined

c - 我需要用 C 语言创建一个全局数组,其大小由用户输入