简体   繁体   中英

Allocating memory for array of structs

I've a struct like the one who follows:

typedef struct author
{
char letter;
char *name[200];
int counter;
} Aut, *i_aut;

It consists of a char, and array of "Strings" and int. My goal is to allocate space in memory for an array of 30 of this kind of structs, therefore I tried something like the following:

i_aut lista_autores=calloc(30,sizeof(Aut));

However, it always returns "segmentation fault". I tried to initialize one at a time too, but with the same result. My question is, how do I allocate memory of this kind and how can I access it later?

Thank you in advance, and sorry for any typo.

the struct member name is an array of 200 pointers.
You may want to assign the result of malloc to elements of the array.

struct author *i_aut;
i_aut = malloc(sizeof *i_aut);
if (i_aut) {
    for (size_t k = 0; k < 200; k++) {
        i_aut->name[k] = malloc(30);
        if (!i_aut->name[k]) /* error */;
        /* DONT FORGET TO FREE EACH NAME LATER ON */
    }
    free(i_aut);
}

try using this

    struct author **i_aut;
    i_aut=(struct author **)malloc(30*sizeof(struct author*));
    for(i=0;i<30;i++)
        i_aut[i]=(struct *)malloc(sizeof(struct author)); 

after this you need not allocate space for name[] seperately. you have array of 30 elements of type struct author* and you can access all three type using i_aut[i]->letter; i_aut[i]->name[j]; i_aut[i]->counter; here i<30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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