Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

c - Global integer array with No dimension

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
",arr[1]);
      system("PAUSE");  
      return 0;
    }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...