我几周前才开始用 C 编程,我正在尝试理解列表。
在我的程序中,我试图从头开始实现一个列表。我这样做了,但显然我遇到了段错误。我无法修复 :(
我的想法/想法
我认为我的问题出在调用插入函数时。我想调用它,以便将返回结果放回到指针中,指向列表的开头(那将是人)。但我不确定我是否正确实现了这一点。
此外,空闲内存应该在之后调用 我记得列表中的下一个元素在哪里。但我到底该怎么做呢?我应该使用 *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 个 char
(char[32]
) 的数组。 You can't assign to an array in C .使用strcpy
、strncpy
、memcpy
等代替。
然后是:
free(people*);
...这是无效语法。删除 *
:
free(people);
最后是这个:
*insert_start (people, names[i], ages[i]);
...您正在取消引用函数返回的 struct person *
但未对它执行任何操作。
也许你应该看看 Definitive Book Guide .
关于C 列表插入程序 - 运行时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20271877/