我剛剛在幾周前開始用C語言編程,並試圖理解列表。C列表插入程序 - 運行時出現分段錯誤
在我的程序中,我試圖從頭開始實現一個列表。我這樣做,但顯然我得到了分段錯誤。對此我無法修復:(
我的想法/思考
我相信我的問題是,當我打電話插入功能,我想打電話給它,以便返回結果被放回指針,但是我不知道我是否正確實現了這個功能
另外,空閒內存應該叫做我記得列表中的下一個元素在哪裏。但是我該怎麼做呢?我應該使用*接下來嗎?你認爲如何?
我的全程序的情況下,你需要它
#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;
}
任何建議,將不勝感激!
謝謝!
薩拉:)
你可以找到這個函數:'insert'在你的代碼中? – this
使用'strcpy'爲你的char []拷貝 – Antoine
插入函數被稱爲「insert_start」。我只是在我的帖子中更新了這一點。 – Sarah