C pointer pointer, and seg fault

后端 未结 4 1380
不思量自难忘°
不思量自难忘° 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

    You have a fundamental misunderstanding of reference semantics via pointers. Here's the core example:

    // Call site:
    T x;
    modify(&x);         // take address-of at the call site...
    
    // Callee:
    void modify(T * p)  // ... so the caller takes a pointer...
    {
        *p = make_T();  // ... and dereferences it.
    }
    

    So: Caller takes address-of, callee dereferences the pointer and modifies the object.

    In your code this means that you need to say *headRef = newNode; (in our fundamental example, you have T = struct node *). You have it the wrong way round!

提交回复
热议问题