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;


typedef struct lista_tlumaczen{
char znak;
WYRAZ *lista_znakowa;

I want to have something like that


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:


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:


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:


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