零长度数组与指针 [英] zero length arrays vs. pointers

查看:23
本文介绍了零长度数组与指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然其中一些在各种 C 标准中是不允许的/已经改变.为了我自己假设的好处,让我们假设我们正在使用 gcc test.c 没有标准或警告选项.

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

这两种情况之间是否还有其他一些我不知道的区别(除了 sizeof)?

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.

推荐答案

我见过零长度数组实际使用的唯一一次是当你想要一个可变长度结构时.

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

在这个例子中取自这里

    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.

如果你在上面的结构上做一个 sizeof ,它不包括任何内容的空间.我不确定这是否曾经成为标准,它会在各种编译器上发出警告.

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.

这篇关于零长度数组与指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆