在下面的代码中有两个结构。一个名为person的人和一个名为person_list的人名单,该名单通过引用来保存人员结构或“人物”的列表。
我想在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];
}
}
答案 0 :(得分:0)
@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);
}