我试图找出为什么我的链表在以下程序结构中被修改:
void edit(NODE pHead)
{
/* Why is this modifying my list ?? */
pHead->data = 1337;
}
void call(NODE *pHead)
{
NODE pFirst = *pHead;
for(int i = 0; i < 3; i++)
{
edit(*pHead);
*pHead = (*pHead)->next;
}
*pHead = pFirst;
printList(*pHead);
}
int main(int argc, char const *argv[])
{
/* A simple list */
NODE pList = NULL;
/* The number of nodes */
int n;
scanf("%d", &n);
/* Init list */
for (int i = 0; i < n; i++)
{
//Read values.
int timestamp;
float data;
scanf("%d%f", ×tamp, &data);
//Add node.
addLastNode(&pList, timestamp, data);
}
printList(pList);
call(&pList);
return 0;
}
我根本不明白这一点。编辑功能不是应该创建我的链接列表的本地副本吗? 打印我的最终列表时,输出是修改后的列表,而不是原始列表。有人可以向我解释一下出了什么问题吗?这也是我的列表结构:
/* A structure representing the node of a list */
typedef struct LIST
{
int timestamp;
float data;
struct LIST *next;
} * NODE;
最佳答案
Isn't the edit function supposed to create a local copy of my linked list?
有
void edit(NODE pHead) { /* Why is this modifying my list ?? */ pHead->data = 1337; }
和
typedef struct LIST { int timestamp; float data; struct LIST *next; } * NODE;
NODE 是指向 LIST 的指针,因此在编辑中单元格不是 一个副本,当你修改它时修改的不仅仅是本地
就是这样:
void edit(struct LIST * pHead)
{
/* Why is this modifying my list ?? */
pHead->data = 1337;
}
这就是与:
的区别 void edit(struct LIST pHead)
{
pHead.data = 1337;
}
其中单元格是本地的并且修改对外部没有影响
这就是为什么永远不要使用 typedef 来隐藏指针,因为这会让你假设在操作指针时操作一个值
关于C 链表在指针传递时被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55244477/