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
463 views
in Technique[技术] by (71.8m points)

c - zero length arrays vs. pointers

EDIT: apparently some of this isn't allowed/has changed in various C standards. For my own hypothetical benefit, let's pretend we're using gcc test.c with no standard or warning options.

In particular I'm looking at the under-the-hood specifics. I've added my current understanding. Am I right?

char **c1;   //Size for a pointer is allocated on the stack. sizeof(c1) == sizeof(void*)
char *c2[0]; //Nothing is allocated on the stack.  sizeof(c2) == 0

is there some other difference between these two cases I'm not aware of (besides sizeof)?

struct a {
   int i;
   char c[0]; //sizeof(a) is sizeof(int)?  a.c == (&i)+1?
};

As I understand it, this is typically used for variable length arrays at the end of structures. But what about

struct b {
   char *c[0] //sizeof(b) is 0?  where does c point?
};

int j;
struct b myb; //myb.c == (&j)+1 == $esp?

Furthermore, how is the address of a zero length array known if space for its pointer is never allocated anywhere? I suppose the same way a regular array's address is known, but I'm struggling to wrap my mind around it at the moment.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The only time I've ever seen zero-length arrays actually used is when you want to have a variable length structure.

As in this example taken from here

    struct line {
       int length;
       char contents[0];
     };

     struct line *thisline = (struct line *)
       malloc (sizeof (struct line) + this_length);
     thisline->length = this_length;

You don't want to use a pointer in the above struct as you want the contents to be part of the allocated memory of the structure.

If you do a sizeof on the above struct it doesn't include any space for the contents. I'm not sure if this ever made it into a standard, it gives warnings on various compilers.


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

...