p
in your structure is a pointer to an int
, not an array. So it won't compile. You should use zero-length array or flexible array member to dynamically allocate memory for it. However, it must be the last struct member. Here is how you declare it.
struct tode {
int g;
int p[]; // p is a zero length array here, not a pointer
};
// sizeof(tode) is 4 on a 32-bit machine
It is one of the few cases where you can declare a zero-length array (other I recall is when you declare an extern
array). Since a zero-length member is an incomplete type, you must first allocate memory, and then you can do any operation with it.
struct tode *lp = malloc(sizeof(tode) + 10*sizeof(int));
// after you are done with lp
free(lp);
Here, the 10*sizeof(int)
part in the malloc
argument dynamically allocates the array. sizeof(tode)
doesn't take into account p
because it's an incomplete type.
After the above statement, p
is an array of 10 int
s.
However, if you did this
struct tode {
int g;
int *p; // p is a pointer
};
// sizeof(tode) is 8 on a 32-bit machine
Then you would dynamically allocate the structure as
struct tode *lp = malloc(sizeof(tode));
// lp->p is of type (int *) so it can contain any int address
lp->p = malloc(10 * sizeof(int));
// after you are done with lp
free(lp->p);
free(lp);
You can also allocate and initialize your structure on the stack using designated initializer (C99) as showed by Jens
struct tode lv = {.g = 10, .p = malloc(10 * sizeof(int))};
However, before the variable lv
goes out of scope, you should free
the memory pointed to by lv.p
as
free(lv.p);