将typedef结构作为C中的引用传递

时间:2014-05-19 09:25:14

标签: 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,即使在成功分配内存后,我也无法使用新创建的节点获取头值。仍然将值显示为NULL。

我已经使用gdb进行了调试,发现在代码之下,head不是NULL

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

我以为我通过引用传递并期望该值反映在调用函数中。

请指正。

1 个答案:

答案 0 :(得分:5)

如果要在C中通过引用(或者说等效)传递,则必须传递指针。要通过引用传递指针,您必须将指针传递给指针。

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

void insert_into_list(node_t **head, int value)

访问head变量时使用解除引用运算符。

您可以使用地址操作符&来调用它:

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