简体   繁体   中英

Initialization array in a struct

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?

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 .

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);

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM