我遇到了以下代码。为什么使用*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
作为 int
的 5 元素数组。就好像我已将结构定义为
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
的每个实例大小相同。
- 这很方便,因为 VLA 可能不是“struct”类型的成员。
关于c - 为什么在 C 中使用 char* arr[1] ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37350939/