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 に答える