C pointer pointer, and seg fault

后端 未结 4 1375
不思量自难忘°
不思量自难忘° 2021-01-24 03:47

Below is my simple linked list in C. My question is in \"headRef = &newNode;\" which causes segmentation fault. Then I tried instead \"*headRef = newNode;\" which resolves the s

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-24 04:08

    newNode is already an address, you've declared it as a pointer: struct node *newNode. With *headRef = newNode you're assigning that address to a similar pointer, a struct node * to a struct node *.

    The confusion is that headRef = &newNode appears to be similarly valid, since the types agree: you're assigning to a struct node ** another struct node **.

    But this is wrong for two reasons:

    1. You want to change the value of your function argument headRef, a struct node *. You've passed the address of headRef into the function because C is pass-by-value, so to change a variable you'll need it's address. This variable that you want to change is an address, and so you pass a pointer to a pointer, a struct node **: that additional level of indirection is necessary so that you can change the address within the function, and have that change reflected outide the function. And so within the function you need to dereference the variable to get at what you want to change: in your function, you want to change *headRef, not headRef.
    2. Taking the address of newNode is creating an unnecessary level of indirection. The value that you want to assign, as mentioned above, is the address held by newNode, not the address of newNode.

提交回复
热议问题