Reputation: 14179
I don't understand why I got an error when I try to initialize a struct in such a way
typedef struct _floor
{
int room;
int height;
int room_dim[room][2];
}Floor;
Why can't I use room to initialize room_dim array?
Upvotes: 1
Views: 180
Reputation: 876
you can instead use malloc to get the dynamic memory rather then using room_dim[room][2] .Since the above is not the allowed standard in c compiler.
for example
typedef struct floor
{
int *room_dim[];
int height;
int room;
}floor;
scanf("%d",&room);
floor.room_dim=(floor *) malloc(sizeof(floor)*room);
Upvotes: 1
Reputation: 179382
A struct
must have a size that is known at compile-time. room
is a struct variable, and could have any value; therefore, it is not a compile-time constant and cannot be used to size a struct
member.
Instead, you can make the final element a flexible array member and allocate it at runtime:
struct floor {
int rooms;
int height;
int room_dim[][2];
};
struct floor *make_empty_floor(int rooms) {
struct floor *ret = malloc(sizeof(struct floor) + sizeof(ret->room_dim)*rooms);
ret->rooms = rooms;
return ret;
}
Now you can use ret->room_dim
as usual, and the extra malloc
'd space will be used for room_dim
.
Upvotes: 5
Reputation: 1065
You are trying to dynamically initialize an array. This means you will only know the size of room at run time.
[Edited after comments]
To understand it simply, without use of struct
, even this won't compile below C99, however in structs this is still not allowed
int n;
int size[n];
Upvotes: 1