繁体   English   中英

为包含指向不同结构的指针数组的结构填充数据

[英]Filling in data for a struct that holds an array of of pointers to a different struct

在下面的代码中,有两个结构。 一个被称为人员的人员和一个称为人员_列表的人员,通过引用保存人员结构或“人员”的列表。

我想在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);

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM