在下面的代码中,有两个结构。一个称为人员的人员和一个称为人员列表的人员,通过引用保存人员结构或“人员”的列表。
我想在person_list中填写(或引用)10个人的结构,但是运行此代码后,我遇到了段错误。我该如何处理或声明每个人的记忆,以便起作用?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 50
#define MAX_PEOPLE_ALLOWED 10
struct person_list {
struct person *people[MAX_PEOPLE_ALLOWED];
};
struct person
{
char name[MAX_LENGTH];
//int age;
};
int main(int argc, char *argv)
{
struct person_list list;
struct person pers[10];
int i;
char name[MAX_LENGTH];
for (i = 0; i < MAX_PEOPLE_ALLOWED; i++) {
sprintf(descrip, "I am person number: %d", i);
strcpy( &pers[i].name, name);
list.people[i] = &pers[i];
}
}
最佳答案
@BDillan,我对您的代码做了一些简单的更正,希望您正在寻找与此类似的内容
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 50
#define MAX_PEOPLE_ALLOWED 10
struct person_list {
struct person *people[MAX_PEOPLE_ALLOWED];
};
struct person
{
char name[MAX_LENGTH];
//int age;
};
int main()
{
struct person_list list;
struct person pers[10];
char descrip[MAX_LENGTH];
int i;
char name[MAX_LENGTH];
for (i = 0;i < MAX_PEOPLE_ALLOWED; i++)
{
sprintf(descrip, "I am person number: %d", i);
strcpy(pers[i].name,descrip);
//puts(pers[i].name);
list.people[i] = &pers[i];
}
//to display the details of persions entered above
for (i = 0;i < MAX_PEOPLE_ALLOWED; i++)
printf("%s \n",list.people[i]->name);
}
关于c - 填充包含指向不同结构的指针数组的结构的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29403856/