c - 指向结构的指针数组 - 为什么需要 malloc(),为什么需要直接字段复制?

标签 c pointers struct malloc

我认为我对 C 中的内存和指针有一个根本性的误解。我想问一下,为什么指向结构的指针数组需要为数组的各个元素调用 malloc(),即使我认为如果它们是单独初始化的,那么应该为它们自动分配内存。其次,在填充指针数组时,似乎有必要单独复制结构的元素,而简单地将指针复制到结构本身是行不通的。

在其他程序中,我一直在使用结构体和指针,我一直在寻找实现它们的正确方法,所以我想直观地理解它,而不是仅仅理解“你只需要到 malloc() 数组的各个元素”

/* suppose I have "typedef struct coord { int x; int y; } coord;" */
int num_rooms = 5;
coord* coordinates[num_rooms];
int i, j;
/* why is this required? in the following loop, coord[i] gets initialized,
and I thought memory automatically gets allocated on the stack because of 
the initialization */
for (i = 0; i < num_rooms; i++) {
    coordinates[i] = (coord*) malloc(sizeof(coord));
}
/* fill the array of coord pointers */
for (j = 0; j < num_rooms; j++) {
    coord coordinate;
    coord *coord_p;
    coord_p = &coordinate;
    coord_p->x = j;
    coord_p->y = j;

    /* this does not work. It just makes all array elements have the same struct elements. (the second question) Why does it require copying over individual field elements instead of copying the pointer?*/
    //coordinates[j] = coord_p;

     /* however, assigning individual elements doesn't cause segmentation fault */
     coordinates[j]->x = coord_p->x;
     coordinates[j]->y = coord_p->y;
} 

如果我取消对 coordinates[i] = coord_p; 的注释,结果是数组的所有元素都具有最后一个初始化元素的结构元素。因此,如果我打印每个 coordinate[i]->x 和 coordinate[i]->y 它会说“4 4” 5 次。但是当我使用直接结构元素副本时,如果我打印它,我会得到正确的输出 '0 0, 1 1, 2 2, ...'。

我希望不为数组的单个元素分配内存应该没问题,因为它们是在循环中初始化的。我还希望 coordinates[i] = coord_p; 应该复制指针值,让 printf("%d", coordinates[0]->x); 正常工作。但是,在这两种情况下,我显然都误解了一些东西。

最佳答案

...why an array of pointers to structs needs malloc() called for individual elements of the array even though I'd think if they're getting initialized individually, then memory should be automatically allocated for them.

简单的答案是,从这个意义上说,C 永远不会“自动”为您分配任何东西。

一种思考方式是 C 为您的命名变量分配足够的内存,仅此而已。如果你说

int i;

C 为一个 int 分配了足够的内存.如果你说

double a[10];

C 为 10 double 分配了足够的内存秒。如果你说

int *p;

C 为一个指向 int 的指针分配了足够的内存,但是它没有为指向该指针的指针分配任何内存!

几乎毫无异常(exception),当您声明指针时,您有责任考虑指针将指向的内存分配。 C 永远不会自动为你做那件事。

在你的具体例子中,当你说

coord* coordinates[5];

C 为 5 个指向 coord 的指针分配了空间-- 但它为 coord 的零个实际实例分配了空间.另一方面,如果你说

coord coordinatesa[5];

C 会为 coord 的 5 个实际实例分配空间-- 尽管您显然会以完全不同的方式使用此数组,因为其中不涉及指针。

当您分配了 5 个指针,但没有 coord 的实际实例时,如果您尝试使用其中一个指针,那将是一个严重的错误:

coord* coordinates[5];
coordinates[0]->x = 1;       /* WRONG */
coordinates[0]->y = 2;       /* WRONG */

解决此问题的一种方法是首先确保 coordinates[0]指向某处:

coord* coordinates[5];
coordinates[0] = malloc(sizeof(coord));
coordinates[0]->x = 1;       /* better */
coordinates[0]->y = 2;       /* better */

Second, when filling up the array of pointers, it seems that it's necessary to copy the elements of the structs individually and simply copying the pointer to the struct itself doesn't work.

啊,但是当你复制指针时,你携带了源指针的分配,而丢失了目标指针的分配。

以我前面的例子为例,如果你要说的话,融入你的程序的一部分

coord* coordinates[5];
coordinates[0] = malloc(sizeof(coord));

coord coordinate;
coord *coord_p;
coord_p = &coordinate;
coord_p->x = 1;
coord_p->y = 2;
coordinates[0] = coord_p;

这会“奏效”,但很浪费,而且可能是错误的。 malloc分配的内存call 从未使用过,当你说

coordinates[0] = coord_p;

旧指针被覆盖,指向的内存(malloc 如此好心地给了你!)丢失了。

这次赋值后,分配coordinates[0]指向的内存是什么coord_p的分配是,在本例中是单个 coord结构coordinate .正如我所说,一开始这似乎“有效”,但如果coordinate是超出范围的局部变量,或者如果您最终将它重新用于 coordinates 中的所有 5 个坐标数组,你会遇到问题。

如果,另一方面,你说

*coordinates[0] = *coord_p;

或者,等价地,

coordinates[0]->x = coord_p->x;
coordinates[0]->y = coord_p->y;

现在您正在从 coord 中获取数据coord_p指向,并安全地将其复制到 coordinates[0] 指向的内存中.这样做后,您 (a) 正确使用了为 coordinates[0] 分配的内存指向,并且(b)将自己与以后发生的任何事情隔离到coord_p指向的内存中.

但是到目前为止,在这种情况下,我们不必使用中间体 coord_p根本没有指针。我们也可以说

coord coordinate;
coordinate.x = 1;
coordinate.y = 2;

*coordinates[0] = coordinate;

或者,等价地,

coordinates[0]->x = coordinate.x;
coordinates[0]->y = coordinate.y;

关于c - 指向结构的指针数组 - 为什么需要 malloc(),为什么需要直接字段复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57628149/

相关文章:

c++ - 使用 Qt : Invalid conversion from const void* to void* while using QList<Type *const>

C++ 结构指针

c++ - 构造函数、类、 union 、结构

c - 为什么调用函数会修改参数中未给出的指向函数的指针数组的值?

初始化时的 C 结构填充

c - 出于安全考虑使用getenv

c - 未格式化的 C 文件输入/输出

c - GCC 使用 -D 参数定义类似函数的宏

c - 指向结构的空指针,使用宏访问元素

C - 如何将数组指针设置回第一个内存字节