gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:41:38 24 4
gpt4 key购买 nike

我们定义一个没有维度的全局数组是什么概念这显示输出为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com