Mr.Nimelo Mr.Nimelo - 4 years ago 110
C Question

Table of struct allocate C

This is my structure:

typedef struct wyraz{

char *slowo;
char *tlumaczenie;
struct wyraz *nastepny;

}WYRAZ;

typedef struct lista_tlumaczen{
char znak;
WYRAZ *lista_znakowa;
}LISTA_TLUMACZEN;


I want to have something like that

LISTA_TLUMACZEN tab[5];


but dynamic allocation I don't know how to do this, can someone help me?

Answer Source

When you have embedded pointers to structures you need to think of memory allocation in layers. Starting at the highest level first in this case works best. So start with:

LISTA_TLUMACZEN tab[5];

Here you're saying you want a table of pLISTA_TLUMACZEN structures. If you want this to be dynamic, then you need a pointer to a LISTA_TLUMACZEN:

LISTA_TLUMACZEN *tab;

Then to allocate it, you need to determine how big it is. In this case, we'll say NUMBER_OF_ELEMENTS:

tab = (LISTA_TLUMACZEN *)malloc(sizeof(LISTA_TLUMACZEN) * 5);

If you want to be especially safe that the malloc parameter isn't out of range you can use:

tab = (LISTA_TLUMACZEN *)(NUMBER_OF_ELEMENTS <= (SIZE_MAX / sizeof(LISTA_TLUMACZEN)) ? malloc(sizeof(LISTA_TLUMACZEN) * 5) : NULL);

Now we have the dynamically allocated equivalent of your tab[5] data declaration. Note that it's a table of LISTA_TLUMACZEN structures. So the amount of memory to allocate is the product of 5 and the size of the structure.

Your LISTA_TLUMACZEN structure also has a pointer to another structure with more pointers. You can allocate those following the same kind of logic or actually only as needed when the program needs them and freeing them when they're no longer needed (which is the reason for having dynamic allocation). If all you do is pre-allocate everything with malloc then there's no point and you may as well statically declare everything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download