且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

之间的差异*列表和**列表

更新时间:2023-01-14 21:05:54

这条语句之后:

A *list = (A*) malloc(sizeOfA * sizeof(A));

列表是一个指向一个内存块的起始位置,可容纳类型的 sizeOfA 元素结构A 。因此, *名单的类型为结构A ,同样,列表[我] 的类型结构A ,不是指针到结构A的(这将是列表+ I )。

list is a pointer to the starting location of a memory block that can hold sizeOfA elements of type struct A. Thus, *list is of type struct A, and similarly, list[i] is of type struct A, not pointer to struct A (that would be list+i).

如果你想列表[我] 是一个指向结构A ,那么你的第二件$的C $ C.将很正确的,因为你有足够的空间分配的存储空间来保存 sizeOfA 指针结构A 。请注意,您只分配空间来存放指针,而不是实际的结构A 实例。尝试读取列表[I] - 方式>ç将导致不确定的行为

If you want list[i] to be a pointer to struct A, then your second piece of code would be the correct one, since you're allocating a memory location with enough space to hold sizeOfA pointers to struct A. Note that you are only allocating space to hold pointers, not actual struct A instances. Attempting to read list[i]->c will result in undefined behavior.