簡體   English   中英

C列表插入程序-運行時出現分段錯誤

[英]C List Insert Program - Segmentation fault at running

幾周前我才剛開始用C編程,我正在嘗試了解列表。

在我的程序中,我試圖從頭開始實現一個列表。 我這樣做了,但顯然我遇到了細分錯誤。 我無法修復:(

我的想法/想法

我相信我的問題是當我調用insert函數時。 我想調用它,以便將返回結果放回到指針中,再到列表的開頭(也就是人)。 但是我不確定我是否正確實現了這一點。

另外,我記得列表中的下一個元素在哪里之后 ,應該調用空閑內存。 但是我該怎么做呢? 我應該使用* next嗎? 你怎么看?

如果您需要我的完整程序

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

任何建議將不勝感激!

謝謝!

莎拉 :)

(*pointer).name是32個charchar[32] )的數組。 您不能在C中分配給數組 改用strcpystrncpymemcpy等。

然后是:

free(people*);

...這是無效的語法。 刪除*

free(people);

最后,是這樣的:

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

...在取消引用struct person *返回的struct person *的位置,但不對其執行任何操作。

也許您應該看看《 權威書籍指南》

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM