Skip to main content
GameDev.net gamedev.net
🔒 Locked

Need help with initializing an array

Started by Adam4444 Feb 19, 2007 at 3:31 PM 3 replies 900+ views
Original Post
Adam4444
Adam4444
Hmm... Can't initialize my array so it compiles. Anyway it looks like this now:
typedef struct Object_ {
    int x, y;
    int w, h;
    char *image;
} Object;

typedef struct Map_ {
    long length;
    int speed;
    Object objects[];
} Map;

Map game_maps[2] = {
    {
        1000,
        5,
        {{40, 15, 10, 10, "tux.bmp"}}
    }
};
It's on line 19 it fails. But I don't know how it should look like. Some help would be nice. :)
cignox1
cignox1
Ehat is the exact error? Which compiler do you use? I'm not sure at all, but try removing the '2' from the square brackets...
_sms
_sms
Quote:
Original post by Adam4444
Hmm... Can't initialize my array so it compiles.

Anyway it looks like this now:
typedef struct Object_ {    int x, y;    int w, h;    char *image;} Object;typedef struct Map_ {    long length;    int speed;    Object objects[];} Map;Map game_maps[2] = {    {        1000,        5,        {{40, 15, 10, 10, "tux.bmp"}}    }};
It's on line 19 it fails. But I don't know how it should look like. Some help would be nice. :)


You need to declare the length of array of Objects in the Map_ struct, or declare it as a pointer to Object (Object*) and make a dinamic initialization with new or malloc.
Zahlman
Zahlman
    Object objects[];


This does not - cannot - declare an array of Objects embedded within the struct, because no size is given. Instead it declares a pointer embedded within the struct, that will need to be pointed at some other region of memory (likely a dynamic allocation) where the Object instances will be stored. You just can't initialize them like that. (The reason it works for char*s is that char*s are special: the string literals can be embedded into the static segment of the executable, and the struct is initialized with a pointer value that is known at compile-time. However, equivalent syntax doesn't exist for other types.)

You should be able to initialize the Object array separately, and then initialize the Map with a pointer to that array:

Object game_objects[1] = { {40, 15, 10, 10, "tux.bmp"} };Map game_maps[1] = { { 1000, 5, game_objects } };


However, this all smells very much like you are doing things wrong. For starters, are you actually working in C, or simply carrying over a full set of bad habits to C++? Also, why not read the data from a file?
Adam4444
Adam4444
Damn, that was stupid of me. :S Thanks for the help though.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.