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

时间:2019-03-19 15:22:54

标签: 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;

1 个答案:

答案 0 :(得分:1)

  

不是应该使用编辑功能来创建链接列表的本地副本吗?

拥有

void edit(NODE pHead)
{
     /* Why is this modifying my list ?? */
     pHead->data = 1337;
 }

typedef struct LIST
{
    int timestamp;
    float data;
    struct LIST *next;
 } * NODE;

节点指向的指针,所以在 edit 中,单元格不是 副本,并且在修改时,修改不仅是本地的

就是这样:

void edit(struct LIST * pHead)
{
     /* Why is this modifying my list ?? */
     pHead->data = 1337;
 }

与:的区别是

 void edit(struct LIST pHead)
 {
     pHead.data = 1337;
 }

该单元格位于本地且修改对外部没有影响

这就是为什么从不使用typedef来隐藏指针的原因,因为这使您假设在操作指针的同时就操作了一个值

相关问题