C 链表在指针传递时被修改

标签 c pointers linked-list

我试图找出为什么我的链表在以下程序结构中被修改:

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", &timestamp, &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/

相关文章:

c - 在 printf 语句中插入 'n' 制表符

c - 指针操作

c - memset 空指针数组

java - 如何使用链接列表中的对象

c - 为什么 C bool 值称为 _Bool?

c - msgid 创建错误

c - Ansi C int16_t 对 int8_t 数组的引用

c++ 解决方案在 leetcode 上失败,地址未对齐错误,但在 Visual Studio 中运行

c - C 中获取链表的第 n 个值

algorithm - 合并排序链表