【发布时间】:2018-06-16 06:22:07
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
void init(node* head, node* tail){
head = (node*)malloc(sizeof(node));
tail = (node*)malloc(sizeof(node));
head->next = tail;
tail->next = tail;
}
void push(node* head, int data){
node *temp;
temp = (node*)malloc(sizeof(node));
if(temp == NULL){
printf("%s", "Out Of Memory");
}else{
temp->data = data;
temp->next = head->next;
在下一行,有 printf 方法打印数字 7。 是用来调试的。但是这个 printf 方法没有用。所以我注意到了
temp->next = head->next;
此代码有错误。但我找不到原因。。 我在考虑内存分配问题。但还是没明白..!
printf("%d", 7);
head->next = temp;
printf("push (%d)", data);
}
}
void main(){
node* head = NULL;
node* tail = NULL;
init(head, tail);
push(head, 10);
}
【问题讨论】:
-
拥有
init函数并没有错,但要明白,当将指针传递给函数时,函数会收到指针的副本(带有自己的和非常不同的指针地址)。因此,如果您需要传递和分配指针而不返回和分配新的内存地址,则需要将指针的地址作为参数传递(例如node**,并调用使用init(&head, &tail);),以便您在init函数中对同一指针进行操作。否则,您将新地址分配并分配给副本,并且在main()中永远不会看到更改。 -
printf("%s", "Out Of Memory")->printf("Out Of Memory")不需要"%s" -
temp->next = head;
标签: c data-structures linked-list