c - 迭代存储在堆上的数组

标签 c arrays pointers memory

请考虑以下代码:

// 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/

相关文章:

c++ - 为 Pimpl 使用不透明指针的更好方法

c - 关于 SNMP 中代理的 MIB 处理

java - 如何声明数组元素为空?

arrays - 将整数数组拆分为 3 个总和相等的数字 block

Java,填充数组和继承

c - 在 C 中的单独函数中初始化指针

c - #176-D expression has no effect”警告,当我创建一个函数指针数组时。这是怎么回事?

C 用 fgets 读取多行

c - 临时为算术转换 void* 的正确方法是什么?

iphone - 从相机输入复制像素