gpt4 book ai didi

c - C `=` 运算符在结构之间应用时是否复制内存?

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:03 24 4
gpt4 key购买 nike

考虑这个例子:

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 结构的数组分配空间。

ReallyBigItem* item = (ReallyBigItem*) malloc(sizeof(ReallyBigItem));

我正在为 ReallyBigItem 分配空间,并将它的内存地址存储在 item 中。

array[0] = *item;

现在我将数组的第一个元素设置为该项目。

我的问题是:

= 运算符实际上是在已分配的内存上复制吗?所以项目结构在内存中存在两次

最佳答案

So the item struct exists in memory twice?

item 指向的struct 的内容在赋值后存在两次,是的。

解释:

这个表达式的两个操作数

array[0] = *item;

评估一个struct

= 是为struts 定义的。

所以上面的表达式将数据(内存的内容,而不是你所说的“内存”)从右边的 struct 复制到左边。

如果考虑到 *item 实际上与 item[0] 相同,这可能会更明显,所以上面的表达式等同于:

array[0] = item[0];

关于c - C `=` 运算符在结构之间应用时是否复制内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36871142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com