我有以下 C 程序。当我包含以下行时它会起作用,否则会出现分段错误:
printf("head(%p), last(%p), newnode(%p)\n", head, last, newnode);
知道这里有什么问题吗?
这是我的整个程序。这是一个基本的循环队列示例。
#include "stdio.h"
#include "malloc.h"
struct node {
int data;
struct node *next;
};
typedef struct node NODE;
void display(NODE *);
int main(void) {
NODE *head, *last, *newnode = NULL;
int i = 5;
for ( ; i > 0; i--) {
newnode = (NODE *) malloc(sizeof(NODE));
newnode->data = i*10;
newnode->next = NULL;
//printf("head(%p), last(%p), newnode(%p)\n", head, last, newnode);
if (head == NULL) {
head = newnode;
last = newnode;
} else {
last->next = newnode;
last = newnode;
}
last->next = head;
}
display(head);
return 1;
}
void display(NODE *head) {
NODE *temp = NULL;
temp = head;
printf("Elements --> ");
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}