gpt4 book ai didi

c - 为什么我的链表第一个节点有垃圾数据?

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:59 25 4
gpt4 key购买 nike

我列表的第一个节点似乎有垃圾数据。为什么会这样?

这些是我正在使用的结构的定义。

typedef struct node { 
char *x;
struct node *next;
}node;

typedef struct {
struct node *head;
}list;

//create_list() 函数:

list* create_list(){
list *myList = malloc(sizeof(myList));
myList->head = NULL;
if (myList->head != NULL){
return NULL;
}
return myList;
}

这里是add_to_list函数的实现

int add_to_list(list* ll, char* item){

node *current = ll->head;
node *new_node = malloc(sizeof(node));
if (!new_node){
fprintf(stderr, "error allocating mem.\n");
return 1;
}
strcpy(new_node->x, item);
new_node->next = NULL;
if(ll->head == NULL){
ll->head = new_node;
return 0;
}else{
while(current->next){
current = current->next;
}
current->next = new_node;
}
return 0;
}

这是 print_list();功能

void print_list(list *ll){

node *current = ll->head;
while(current){
printf("%s\t\n",current->x);
current = current->next;
}
}

当我调用 main.c 中的函数时,我是这样做的:

list *newList = create_list();

char test_var = 'k';

add_to_list(newList, &test_var);

printf("printing whole list : \n");

print_list(newList);

最佳答案

这是因为您将 char 作为 char 指针(即字符串)传递。改变

char test_var = 'k'; 

char *test_var = "k";

并将调用更改为

add_to_list(newList, &test_var)

add_to_list(newList, test_var)

关于c - 为什么我的链表第一个节点有垃圾数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46146700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com