简体   繁体   中英

linked list and segmentation fault error in my code

my code is the following: it asks the user to input name of planet, distance, and a description. Then it will print out whatever the user entered.

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

the places where i made comments are the where i am not sure if it is correct, the code complies but gives me a segmentation error. any help? thanks.

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

This is where your error is. It should be:

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

Also an extra ' ' causes it to accept extra characters. This can be avoided with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM