我的代码如下:它要求用户输入行星名称,距离和描述。然后它将打印出用户输入的内容。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* planet type */
typedef struct{
char name[128];
double dist;
char description[1024];
} planet_t;
/* my planet_node */
typedef struct planet_node {
char name[128];
double dist;
char description[1024];
struct planet_node *next;
} planet_node;
/* the print function, not sure if its correct */
void print_planet_list(planet_node *ptr){
while(ptr != NULL){
printf("%s %lf %s\n", ptr->name, ptr->dist, ptr->description);
ptr=ptr->next;
}
printf("\n");
}
int main(){
char buf[64];
planet_node *head = NULL;
int quit = 0;
do {
printf("Enter planet name (q quits): ");
scanf("%s",buf);
if((strcmp(buf,"q")==0)){
quit = 1;
}
else{
planet_node *new = malloc(sizeof(planet_node)); /* New node */
strcpy((*new).name, buf); /* Copy name */
printf("Enter distance and description: ");
scanf(" %lf ", new->dist); /* Read a new distance into pluto's */
gets(new->description); /* Read a new description */
new->next = head; /* Link new node to head */
head=new; /* Set the head to the new node */
}
} while(!quit);
printf("Final list of planets:\n");
print_planet_list(head);
while(head != NULL){
planet_node *remove = head;
head = (*head).next;
free(remove);
}
}
我发表评论的地方是我不确定它是否正确的地方,代码符合但给我一个分段错误。 任何帮助?感谢。
答案 0 :(得分:3)
scanf(" %lf ", new->dist);
这是您的错误所在。 它应该是:
scanf(" %lf ", &(new->dist));
另外一个''会使它接受额外的字符。
可以避免这种情况 scanf("%lf", &(new->dist));