Accessing pointer to pointer of struct using -> operator

馋奶兔 提交于 2020-06-09 04:48:04

问题


I have this code:

#include<stdio.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node *next;
};

void pointerOfPointer(struct node **reference)
{
    struct node *temporary = malloc(sizeof(struct node));

    temporary->data = 100;
    temporary->next = 0;

    printf("before: temporary->data %d\n", temporary->data);
    temporary = *reference;
    printf("after: temporary->data %d\n", temporary->data);
}

int main()
{
    struct node *linkedlist = malloc(sizeof(struct node));
    linkedlist->data = 15;
    linkedlist->next = 0;
    pointerOfPointer(&linkedlist);
    return 0;
}

How can I access the pointer to pointer of struct in the pointerOfPointer function without copying the *reference address to the temporary local variable? So in the end I can access the reference variable data using operator -> directly, like reference->data?


回答1:


Remember that foo->bar is just syntactic sugar for (*foo).bar. What you're asking for is essentially (**reference).data, which you can rewrite as (*reference)->data if you want.



来源:https://stackoverflow.com/questions/42498902/accessing-pointer-to-pointer-of-struct-using-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!