注意:这篇文章上次更新于1443天前,文章内容可能已经过时。
This article was last updated1443 days ago, the content may be outdated.
有时候会看到类似如下情况声明的结构体,这个结构体中的 intro 有什么深意吗?
Sometimes you may see a struct declared like the one below. What is the meaning of the
intromember in this struct?
1 | typedef struct{ |
这个例子中结构体的前两个字段平平无奇,一个是整型变量,一个指针变量。那么长度为零的数组有什么用呢?和指针有什么区别呢。
首先,数组的名字是一个地址,指向的是结构体内的一块空间,指针是可以指向任意位置的,但是数组是不可以的,这是数组和指针的区别。
之所以声明一个长度为 0 的数组,是为了可以在定义时控制其长度,以实现变长数组的效果。
比如使用如下函数初始化结构体。
In this example, the first two fields of the struct are unremarkable — one is an integer variable, and the other is a pointer variable. So what is the use of an array with zero length? What is the difference between it and a pointer?
First of all, the name of an array is an address that points to a space inside the struct, while a pointer can point to any location — an array cannot. This is the difference between arrays and pointers.
The reason for declaring an array of length 0 is to be able to control its length at definition time, achieving the effect of a variable-length array.
For example, initialize the struct with the following function.
1 | Person* PersonNew(const char* name,int age,const char* intro) |
在这个初始化函数中,首先计算 intro 字符串所需要的空间大小,然后动态申请 Person 结构体的空间,最后将 intro 的内容复制到结构体中。
还可以写出其他的操作此结构体的函数。
In this initialization function, the space required for the intro string is calculated first, then the memory for the Person struct is dynamically allocated, and finally the intro content is copied into the struct.
Other functions that operate on this struct can also be written.
1 | // 打印信息 |


