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/39585465/

相关文章:

c - 如何为 fork 和执行的程序组织文件系统?

c++ - 如何在不需要 LIBCD.lib 的情况下在 Visual Studio 6 中编译 C 项目?

c - ARM C中main中声明的全局变量和变量的区别

c - 显示记录功能以显示非空记录不显示记录

javascript - 在 Javascript 中过滤数组以查找 3 个连续的数字

java - ArrayList 中数组的 ArrayAdapter

java - 在方法参数java中调用二维数组

Python 非本地语句/关键字

testing - 我怎样才能避免全局状态?

c - 从 C 程序执行命令行