I have problem in accessing the pointer to a structure (array passed to function) that has a variable size array.
char name[20];
char value[20];
}param_t;
typedef struct object {
char name[20];
int no_of_params;
param_t params[];
};
int main()
{
int no_of_objs = 3, no_of_params = 5;
object_t *objs = malloc(no_of_objs * (sizeof(object_t) + (no_of_params * sizeof(param_t)) );
//...
//...
objs++; //Increment to point to the next item <-- Problem: ignores params[] size
// blah
// blah
// blah
I have allocated memory to have 3 object_t with each object_t storing 5 param_t.
Memory allocation is fine and I could set values to the members. objs[0] is perfectly fine. Now if I increment the objs (objs++) to point to next object, it actually points to previous object's param address. It completely ignores the params[]. Now if I set values for the second *objs, it actually overwrites the params[] of previous *objs.
My question is: Is this a bug in C compiler? If not, how do I traverse the objs?
As per the answer of Bathsheba, you could better implement it as an array of pointers to the objects:
int no_of_objs = 3, no_of_params = 5;
object_t **objs = malloc(no_of_objs * sizeof(object_t *);
for (int i=0; i<no_of_objs; i++)
objs[i]= malloc ((sizeof(object_t) + (no_of_params * sizeof(param_t)) );
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments