C `=` 运算符在结构之间应用时是否复制内存?
Is the C `=` operator copying memory when applied between structs?
考虑这个例子:
typedef struct {
int x;
int y;
...
} ReallyBigItem;
ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);
ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));
item->x = 0;
item->y = 1;
array[0] = *item;
ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);
我正在为适合 8 个 ReallyBigItem
结构的数组分配 space。
ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));
我正在为 ReallyBigItem
分配 space 并将其内存地址存储在 item
中。
array[0] = *item;
现在我将数组的第一个元素设置为该项目。
我的问题是:
=
运算符实际上是在 复制 已经分配的内存吗?所以项目结构在内存中存在两次?
是的,您正在复制整个 struct
。您可以创建一个 ReallyBigItem **array
并分配 item
(而不是 *item
)来复制指针。
So the item struct exists in memory twice?
item
指向的struct
的内容在问题赋值后存在两次,是的。
解释:
这个表达式的两个操作数
array[0] = *item;
评估为 struct
。
=
是为 struts
定义的。
所以上面的表达式从右边struct
向左边复制数据(内存的内容,而不是你所说的“内存”)。
如果考虑到 *item
实际上与 item[0]
相同,这可能会更明显,因此上面的表达式等同于:
array[0] = item[0];
是的,确实如此。您复制整个结构。
代码:
#include <stdio.h>
typedef struct {
int x;
int y;
} ReallyBigItem;
int main(void) {
ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);
ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));
item->x = 0;
item->y = 1;
array[0] = *item;
printf("%d - %d\n", array[0].y, item->y);
}
考虑这个例子:
typedef struct {
int x;
int y;
...
} ReallyBigItem;
ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);
ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));
item->x = 0;
item->y = 1;
array[0] = *item;
ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);
我正在为适合 8 个 ReallyBigItem
结构的数组分配 space。
ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));
我正在为 ReallyBigItem
分配 space 并将其内存地址存储在 item
中。
array[0] = *item;
现在我将数组的第一个元素设置为该项目。
我的问题是:
=
运算符实际上是在 复制 已经分配的内存吗?所以项目结构在内存中存在两次?
是的,您正在复制整个 struct
。您可以创建一个 ReallyBigItem **array
并分配 item
(而不是 *item
)来复制指针。
So the item struct exists in memory twice?
item
指向的struct
的内容在问题赋值后存在两次,是的。
解释:
这个表达式的两个操作数
array[0] = *item;
评估为 struct
。
=
是为 struts
定义的。
所以上面的表达式从右边struct
向左边复制数据(内存的内容,而不是你所说的“内存”)。
如果考虑到 *item
实际上与 item[0]
相同,这可能会更明显,因此上面的表达式等同于:
array[0] = item[0];
是的,确实如此。您复制整个结构。
代码:
#include <stdio.h>
typedef struct {
int x;
int y;
} ReallyBigItem;
int main(void) {
ReallyBigItem* array = (ReallyBigItem*) malloc(sizeof(ReallyBigItem) * 8);
ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));
item->x = 0;
item->y = 1;
array[0] = *item;
printf("%d - %d\n", array[0].y, item->y);
}