【问题标题】:int a[0]; What is the use of this statement? Where does it makes sense? [duplicate]整数[0];这个说法有什么用?它在哪里有意义? [复制]
【发布时间】:2014-06-06 12:58:15
【问题描述】:

我在结构末尾的驱动程序中看到了这个语句的用法。 谁能解释一下这个语句的用途是什么?它在内部是如何工作的? 我的意思是编译器会将其视为数组还是变量?

【问题讨论】:

标签: c++ c


【解决方案1】:

在 C 中,通过为固定大小的字段和数组中所需的任何内容分配足够的内存,允许您将可变大小的数组放在结构的末尾是一个技巧。例如:

struct array {
    size_t size;
    int a[]; // strictly, it should be incomplete rather than zero sized
};

struct array * make_array(size_t size) {
    struct array * array = malloc(sizeof (struct array) + size * sizeof (int));
    array->size = size;
    return array;
}

struct array * array = make_array(2);
array->a[1] = 42;  // No problem: there's enough memory for two array elements

在 C++ 中,它是无效的。请改用std::vector

【讨论】:

    【解决方案2】:

    虽然这两个标准都不支持大小为 0 的数组,但许多编译器允许它们作为扩展。标准化的 C 方式 (C99+) 完全忽略了大小。

    Thiis 用于描述由起始字段和可变数量的数组元素组成的数据结构,以及方便地访问它们。

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多