0

我的代码如下:它要求用户输入行星名称、距离和描述。然后它将打印出用户输入的任何内容。

#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);
  }
}

我发表评论的地方是我不确定它是否正确的地方,代码符合但给了我一个分段错误。有什么帮助吗?谢谢。

4

1 回答 1

3

scanf(" %lf ", new->dist);

这就是你的错误所在。它应该是:

scanf(" %lf ", &(new->dist));

额外的 ' ' 也会导致它接受额外的字符。这可以避免

scanf("%lf", &(new->dist));

于 2012-10-23T18:48:27.390 回答