将内存分配给结构数组内的struct指针

时间:2016-11-04 07:15:21

标签: c

如何为struct ptr employee * det分配内存; (对于大小为5)在struct细节数组中?

#include <stdio.h>

#define COMPANY    2
#define MAX        5

typedef struct {
    char *name;
    char *addr;
    int age;
}employee;

struct {
     employee *det;
} details[COMPANY];

int main()
{
    int i;


    for (i=0; i<2; i++)
        details[i].det = malloc(MAX*sizeof(employee *));


return 0;
}

我尝试了以下操作,但失败了,错误:'详细信息'之前的预期表达式

for (i=0; i<2; i++)
    details[i].det = malloc(MAX*sizeof(employee *));

1 个答案:

答案 0 :(得分:0)

例如:

details[i]->det = malloc(sizeof(employee));
details[i]->det->name = strdup("name");
details[i]->det->addr = strdup("address");
details[i]->det->arge = 18;

strdup是malloc和strcpy

的缩写

编辑:

我不太清楚为什么你有额外的&#34;详细信息&#34;介于两者之间,你可以写一下

employee* employees = malloc(sizeof(employee)*5);
...
employees[i]->name = strdup("name");
employees[i]->addr = strdup("address");
employees[i]->arge = 18;