【发布时间】:2016-05-12 05:48:01
【问题描述】:
我需要帮助。我试图创建一个单链表。到目前为止一切都很好,但我得到了错误的输出。我不知道我的错误。谢谢!
我的输出是:
create a single linked list
list:
aaaaa
-1342177280
我的代码是:
struct node{
int key;
int val;
struct node *next;
};
struct node *create_single_link(){
struct node *head = malloc(sizeof(struct node));
head->next = NULL;
return(head);
}
void insertVal( struct node *lst, int v){
struct node *current = malloc(sizeof(struct node));
current -> val = v;
current->next = lst;
lst = current;
}
void print_list(struct node * head){
struct node *ptr = head;
printf("list:\n");
while(ptr != NULL ){
printf("aaaaa\n");
printf("%d \n ",ptr ->val );
ptr = ptr->next;
}
}
int main(int argc, char const *argv[])
{
struct node *list;
list = create_single_link();
if(list != NULL){
printf("create a single linked list\n");
}
else
printf("failed to create a single linked list\n");
insertVal(list,2222);
//insertVal(list,2);
print_list(list);
return 0;
}
【问题讨论】:
-
使用通过
malloc()分配但未初始化的缓冲区中的值调用未定义的行为。 -
你可以看mortoray.com/2012/01/08/whats-an-object-whats-a-variable,你应该知道
pass value和pass reference的区别。