assign zero sized array

Hello.

I'm using a library (allegro) that uses zero size arrays in internal structs, I want to assign another array to it. I've reduced the problem to this code:
1
2
3
4
char array[0];
array= new char[3];
char array2[0];
array2=array;

I use the g++ compiler an get this error message:
error: invalid array assignment
You can't. You can only have one such entry as the last element of the struct.
Last edited on
What is a zero sized array then? I thought it would be very much like a pointer to the actual array data. Isn't that true?
It means the structure is a header immediately followed by an array of things. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct Player
{
    char firstname[25];
    char lastname[25];
    void* extra;
};

class GameInfo
{
    time_t starttime;
    int seedvalue;
    /* other junk */
    unsigned nplayers;
    Player player[0];
};

GameInfo* AllocMem(unsigned nplayers)
{
    size_t sz = sizeof(GameInfo) + nplayers*sizeof(Player);
    if (GameInfo* p = (GameInfo*)operator new(sz))
    {
        p->nplayers = nplayers;
        return p;
    }

    return 0;
}


You then can write code like:
1
2
3
4
5
    if (GameInfo *gameinfo = AllocMem(4))
    {
        strcpy(gameinfo->player[0].firstname, "Bart");
        strcpy(gameinfo->player[1].firstname, "Lisa");
    }
Last edited on
Topic archived. No new replies allowed.