Global integer array with No dimension

狂风中的少年 提交于 2019-12-29 07:42:51

问题


What is the concept when we define a global array with no dimension This shows output as 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;
    }

And even sizeof(arr) doesn't work. Why?


回答1:


int arr[]; is a tentative definition there.

Clause 6.9.2, paragraph 2 says:

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.

and example 2 in paragraph 5 of that clause clarifies:

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.

So at the end of the translation unit, your array arr has type int[1]. Before the end, its type is incomplete, hence sizeof doesn't work, since in main, the array type is still incomplete.

Accessing arr[1] invokes undefined behaviour, since arr has only one element.




回答2:


GCC assumes that arr should only have one element. The fact that you can access other elements than arr[0] without segfaulting is just a coincidence. For instance, on my machine I can access arr[1], arr[10] and arr[100] just fine, but arr[1000] causes a segfault. In general, accessing locations outside array bounds causes undefined behavior.



来源:https://stackoverflow.com/questions/17242690/global-integer-array-with-no-dimension

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