【发布时间】:2014-07-07 04:49:58
【问题描述】:
我正在尝试用 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;
我以为我是通过引用传递并期望值反映在调用者函数中。
请纠正我。
【问题讨论】:
-
从技术上讲,您正在传递一个指针。虽然“通过引用”可以应用于此,但通常不是为了避免与 C++ 中的引用传递混淆(这是不同的)。
-
C 中没有“按引用传递”。如果要初始化指针值本身,则需要将指针的地址向下传递给函数。
-
您正在传递 head 指向“通过引用”的实际节点结构 - 您没有“通过引用”传递 head 指针。把函数改成
void insert_into_list(node_t **,int);,用insert_into_list(&head,10);调用
标签: c pass-by-reference singly-linked-list