我正在尝试用 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/