0

pointer to a struct

code that can not work

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

void addnode(struct node* n)
{
    n = (struct node*)malloc(sizeof(struct node));
    printf("value of pointer n = %p",&n);
    (*n).data = 9;
}
int main()
{   
    struct node * n1 = NULL;
    addnode(n1);
    printf("data is %d\n",n1->data);
}

but the code below is fine

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

void addnode(struct node ** n1)
{
    // the address of struct
    *n1 = (struct node*)malloc(sizeof(struct node));
    printf("address of pointer &n1 = %p\n",&n1);
    printf("address of pointer *n1 = %p\n",*n1);
    (*n1)->data = 99;
}
int main()
{   
    struct node * n1 = NULL;
    //pass the address of pointer instead of value of it
    addnode(&n1);
    printf("address of pointer &n1 = %p\n",&n1); // self address
    printf("address of pointer *n1 = %p\n",&(*n1)); // the address of struct
    printf("data is %d\n",n1->data);
}

what makes me confused is why the indirect pointer as a parameter is working, instead of the direct pointer.

focus zheng
  • 345
  • 1
  • 4
  • 12
  • 1
    @T.J.Crowder Indeed, I once made one as community wiki, see the linked duplicate. A list of good dupe targets can be found in the [C tag wiki](https://stackoverflow.com/tags/c/info) below FAQ. – Lundin Jul 08 '22 at 11:19
  • 1
    In the first version, you just passed the value of `n1` to a function, so `n` just got assigned `NULL` at the beginning. Afterwards you did `n = ... malloc`, which is an unrelated address to the original `n1`. The second version `*n1 =....` writes into the address of what you passed. Also note that your function don't change `&n1` even though it's changed `n1` . So, it's the same value as before you did `addnode(&n1)`, till the very end of the `main`. So: First version: you passed n1 => you can't change n1 from the function Second version: you passed &n1 => you can't change &n1 inside of it – qrsngky Jul 08 '22 at 11:28

1 Answers1

1

The 'indirect' pointer, as you called it, is actually 'a pointer to your pointer variable'.

If you inspect the value of n1 in your debugger, you will see, in your first example, that it will remain NULL (because you did not assign a new value to it).

In the second example however, you assign a value to the variable by accessing it's address.

Your first code can work too if it looks like this:

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

struct node* addnode()
{
    struct node* n = (struct node*)malloc(sizeof(struct node));
    printf("value of pointer n = %p",&n);
    n->data = 9;
    return n;
}
int main()
{   
    struct node * n1 = NULL;
    n1 = addnode();
    printf("data is %d\n",n1->data);
}
Refugnic Eternium
  • 4,089
  • 1
  • 15
  • 24