请考虑以下代码:
// Thing is a typedef struct
void f(Thing* things, int size) {
for (int i = 0; i < size; i++) {
Thing my_thing = things[i];
my_thing.a = 10;
}
}
things
指向的数组分配在堆上的某处。
然而 - my_thing
是一个“堆栈变量” - 在堆栈上分配。
那么幕后发生了什么? things[i]
copied 到堆栈并存储在 my_thing
中了吗? my_thing.a = 10;
做了什么 - 它是修改原始 things[i]
还是修改“堆栈副本”?
最佳答案
Is things[i] copied to the stack and stored in my_thing?
是的,作为内存拷贝,不是深拷贝。
And what does my_thing.a = 10; do - does it modify the original things[i] or does it modify the "stack copy"?
它只修改堆栈副本。但是在处理指针时要小心,参见示例 here
关于c - 迭代存储在堆上的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55697198/