简体   繁体   中英

C List Insert Program - Segmentation fault at running

I just started programming in C a few weeks ago and I am trying to understand lists.

In my program, I am trying to implement a list from scratch. I did that but apparently I am getting a segmentation fault. which I am unable to fix :(

My idea/thinking

I believe my problem is when I call the insert function. I want to call it so that the return result is put back into the pointer, to the start of the list (that would be people). But I am not sure if I implemented that correctly.

Also, free memory should be called after I remember where the next element in the list is. But how exactly do I do that? Should I use *next? What do you think?

My full program in case you need it

#include <stdio.h>
#include<string.h>
#include<stdlib.h> 

/* these arrays are just used to give the parameters to 'insert',
   to create the 'people' array */

#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
              "Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};


/* declare your struct for a person here */
struct person
{ 
    char name [32];
    int age;
    struct person *next; 
}; 


struct person *insert_start (struct person *people, char *name, int age) {

  struct person *pointer = (struct person *) malloc(sizeof(struct person));

    if(pointer == NULL)
    { 
     printf("The program could not allocate memory ");
      exit(-1);
    }

      strcpy((*pointer).name, name);
      (*pointer).age = age;
      (*pointer).next = people;

    return pointer;    
}

int main(int argc, char **argv) {



  /* declare the people array here */
  struct person *people; // need to replace this with a list
  people = 0;   

  int i;
  for (i =0; i < HOW_MANY; i++) 
  {
    insert_start(people, names[i], ages[i]);
  }

  /* print the people array here*/
  for (i =0; i < HOW_MANY; i++)
  {
     printf("%s", people->name);
     printf(" %d\n", people->age);
  }

  for (i = 0; i < HOW_MANY; i++)
    free(people);
  return 0;
}

Any suggestions will be greatly appreciated!

Thank you!

Sarah :)

(*pointer).name is an array of 32 char ( char[32] ). You can't assign to an array in C . Use strcpy , strncpy , memcpy , etc. instead.

Then there's:

free(people*);

...that's invalid syntax. Drop the * :

free(people);

Finally, there's this:

*insert_start (people, names[i], ages[i]);

...where you're dereferencing the struct person * returned by the function but not doing anything with it.

Maybe you should take a look at the Definitive Book Guide .

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