I am a beginner into C programming so I have a basic question, in a lot of places in my code, I use some structures which have two-dim. pointer arrays as a variable, like in this example:
typedef struct example {
char** elements;
int number_elements;
int x;
} example;
So how I did it usually is that I allocate memory for the structure and a number x for the variable elements,
example* e = malloc(sizeof(example);
if (e == NULL) exit(EXIT_FAILURE);
e->elements = malloc(sizeof(char*) * x);
if (e->elements == NULL) //throw error
for (int i=0; i<x; i++) {
e->elements[i] = malloc(sizeof(char)*1024);
if (e->elements[i] == NULL) //throw error
}
So I am adding elements to the 2nd dimension dynamically. So if the 2.nd dimension gets full, I reallocate and update x.
So my question is, is there a nice or common way this number x can be hidden, because like this I store in the structure a variable for the number of elements in it and another variable for the actual number of elements allocated, and this is just ugly.