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

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

问题描述

编辑:显然一些本是不允许/已在多个C类标准的变化。至于我自己假想的利益,让我们pretend我们使用海合会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天全站免登陆