c - 在 C 中通过引用调用传递 typedef 结构

标签 c pass-by-reference singly-linked-list

我正在尝试用 C 语言创建一个链表,我的代码如下。

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


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


void insert_into_list(node_t *,int);
void print_list(node_t *);
node_t *create_node(int );



void insert_into_list(node_t *head, int value){
    node_t *temp ;
    temp = create_node(value);
    if(head == NULL){
        printf("Inserting node for the first time\n");
        head = temp;
    }else {
        head->next = temp;
    }

}
void print_list(node_t *head){
    node_t *current = head;
    while(current!=NULL){
        printf("%d----->",current->data);
        current = current->next;
    }
    printf("NULL");
}
node_t *create_node(int value){
    node_t *new_node = malloc(sizeof(node_t));
    if(new_node==NULL){
        printf("Memory allocation failed for the list creation. :(");
        return NULL;
    }
    new_node->data = value;
    new_node->next = NULL;
    return new_node;
}


int main(int argc, char *argv[]) {
    node_t *head = NULL;
    insert_into_list(head,10);
    if(head==NULL){
        printf("Still head is NULL :(");
    }else{
        printf("Head is not NULL:)");
    }
    print_list(head);
    return 0;
}

main 中,我正在调用 insert_into_list 并且即使在成功分配内存之后,我也无法通过新创建的节点获取 head 值。仍将值显示为 NULL。

我用gdb调试过,发现到下面的代码,head不为NULL

printf("Inserting node for the first time\n");
head = temp;

我以为我正在通过引用传递,并希望该值反射(reflect)在调用者函数中。

请指正。

最佳答案

如果你想在 C 中通过引用(或者更确切地说,等价物)传递,你必须传递一个指针。要通过引用传递指针,您必须传递指向该指针的指针。

所以在例如insert_into_list 您必须将 head 声明为指向指针的指针:

void insert_into_list(node_t **head, int value)

并在访问 head 变量时使用取消引用运算符。

你使用寻址运算符 & 来调用它:

node_t *head = NULL;
insert_into_list(&head,10);

关于c - 在 C 中通过引用调用传递 typedef 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23734155/

相关文章:

c++ - 在cpp LinkedList程序中将两个多项式相乘

c - 请求非结构或 union 中的成员 `result'

c - 指针是否也有任何地址或内存分配?

c++ - 对指针和常量兼容性的引用

android - 将对象从 Activity 传递到 Fragments 是通过引用传递

c - 交换链表中的节点

c++ - 如何指向链表中的下一个节点并打印值

C - 有没有办法让变量在循环之外保持不变?

c - Posix 消息 mq_open 的错误地址

c++ - 可以通过引用将方法从类传递到全局函数或在类之间传递吗?