【发布时间】:2016-04-05 23:37:48
【问题描述】:
我想更好地掌握动态指针。
int main(){
// allocate pointer
randomStructure *pt = (randomStructure *)malloc(sizeof(randomStructure));
// arbitrary code that manipulates data that *pt points to.
// function call
function(pt);
return 0;
}
void function(randomStructure *pt){
randomStructure *tempPt = (randomStructure *)malloc(sizeof(randomStructure));
// arbitrary code that manipulates data that *tempPt points to.
pt = tempPt;
//free(tempPt); Question2
/* Question 4
while(index){
randomStructure *tempPt = (randomStructure *)malloc(sizeof(randomStructure));
}
*/
}
问题:
当我将
*pt传递给函数时,它会自动更新 main 中的*pt还是我需要从函数中返回*pt才能做到这一点?如果我释放函数中的
*tempPt,它是否也会释放*pt?如果我在函数内部 malloc 一个
*tempPt,它指向的数据会在函数结束后自动释放吗?-
这个问题可以从前面的问题中间接回答,但是我如何创建一个
*tempPt并在循环中释放它而不释放*pt以便可以重复该过程?
编辑问题 4:也许我正在尝试做的一个更具体的例子可以澄清这个问题。我正在运行一个基本的启发式算法。在将指针传递给函数后,我操作数据,然后运行算法并使用 *tempPt 指向它。如果 *tempPt 的数据比 *pt 的数据更优化,我想用 *tempPt 的数据更新 *pt。
【问题讨论】:
-
什么是“动态指针”?
-
欢迎来到 Stack Overflow。请不要使用告别辞或签名。 SO 不是讨论列表,它更像是编程问题的在线参考书。简洁和清晰是非常重要的,相反,绒毛是不想要的。请阅读“How to Ask”了解更多信息。
-
我的错。这是我的第一篇文章。非常感谢所有建议!我不完全确定如何调用指向动态分配内存的指针,因此我将其称为“动态指针”。也许我的示例代码会更清楚地说明它?
-
存在许多关于 SO 的现有问题,围绕 C 函数调用的按值参数传递语义,以及它如何与指针交互。
标签: c function pointers dynamic free