【发布时间】:2015-02-15 02:09:58
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
struct data {
int x;
struct data *next;
};
typedef struct data d_t;
/* Main fuction */
int main(){
int x;
d_t test , *root , *head;
scanf("%d" , &x);
/* Sets pointer values */
root=&test;
head=root;
head->next=NULL;
/* While fuction represends "ADD struct to list" */
while(x==1){
/* Allocating memory for new struct */
head=(d_t*)malloc(sizeof(d_t));
head->x=1;
printf("%d\n" , head->x);
/* Sets pointer values for next struct */
head->next=head;
head->next=NULL;
/* Scanfs 'x' to see if user wants to continue */
scanf("%d" , &x);
}
/* Prints Whole list */
while(root!=NULL){
printf("%d --> " , root->x);
root=root->next;
}
return 0;
}
程序应打印:1 --> 1 --> 1---> until NULL。可能出了点问题。提前致谢!
【问题讨论】:
-
不要在 C 中强制转换
malloc,并尝试在调试器中单步执行代码。它是开发人员用来追踪问题的主要工具之一。
标签: c list pointers struct singly-linked-list