c - 为什么在 C 中使用 char* arr[1] ?

标签 c

我遇到了以下代码。为什么使用*child[1]而不是*child

struct _zend_ast {
    zend_ast_kind kind; /* Type of the node (ZEND_AST_* enum constant) */
    zend_ast_attr attr; /* Additional attribute, use depending on node type */
    uint32_t lineno;    /* Line number */
    zend_ast *child[1]; /* Array of children (using struct hack) */
};

最佳答案

这是 struct 的示例hack,您可以在其中定义可变长度数组成员,而无需实际使用可变长度数组1

这可能最好用一个例子来展示。假设struct类型

struct foo {
  int x;
  int arr[1];
};

如果我像这样分配一个结构实例:

struct foo f;

我有足够的空间来容纳 x和一个 1 元素数组 int :

     +---+
  x: |   |
     +---+
arr: |   | arr[0]
     +---+

不是很有用。

但是,如果我像这样为结构分配空间:

struct foo *p = malloc( sizeof *p + (4 * sizeof( int ));

我得到这样的东西:

     +---+
  x: |   |
     +---+
arr: |   | arr[0]
     +---+
     |   | arr[1]
     +---+ 
     |   | arr[2]
     +---+
     |   | arr[3]
     +---+ 
     |   | arr[4]
     +---+

我已经为结构体的所有成员分配了足够的空间,另外还为另外 4 个整数分配了空间。这个额外的空间位于arr之后,这意味着我已经有效地创建了 p->arr作为 int5 元素数组。就好像我已将结构定义为

struct foo {
  int x;
  int arr[5];
};

这与类似的技术不同

struct bar {
  int x;
  int *arr;
};

struct bar *p = malloc( sizeof *p );
if ( p )
{
  p->arr = malloc( sizeof *p->arr * 5 );
}

这给了我这样的东西:

     +---+
  x: |   |
     +---+
arr: |   | ---------+ 
     +---+          |
      ...           |
     +---+          |
     |   | arr[0] <-+
     +---+
     |   | arr[1]
     +---+
     |   | arr[2]
     +---+
     |   | arr[3]
     +---+ 
     |   | arr[4]
     +---+

arr的内存不属于 struct实例本身; struct bar 的每个实例大小相同。


  1. 这很方便,因为 VLA 可能不是“struct”类型的成员。

关于c - 为什么在 C 中使用 char* arr[1] ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37350939/

相关文章:

c++ - 混合使用 C 和 C++ 时出现重复符号

c - 根处理器是否也将 MPI_Reduce 应用于自身?

c - 常量结构内的函数指针

c - 我在哪里放置 xCode 5.1 c 编译器的 .txt 和头文件

c - 如何从图像的直方图中过滤感兴趣的对象?

c - 错误: incompatible types when initializing type 'int' using type ' '

c - 如何加速我的代码?

c++ - 查找加起来等于特定数字倍数的数组子集的数量

c - 我不知道为什么我的 dev c++ #include 不起作用

c - 如何在 C 中合并和排序两个双向链表