Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of struct pointers, invalid initializer error, in C

This code:

extern void *malloc(unsigned int);
struct Box {
    int x, y ,w, h;
};

struct Wall {
    char color[15];
    struct Box *boxes[20];
};

int main(int argc, const char *argv[])
{
    struct Wall *mywall = malloc(sizeof(struct Wall));
    struct Box *myboxes[] = mywall->boxes;
    return 0;
}

gives me invalid initializer error at line 14. What I am trying to do, is to get a copy of array of struct pointers, which are in a different struct.

like image 927
yasar Avatar asked Mar 14 '12 19:03

yasar


1 Answers

Ouch; there are a number of problems here.

extern void *malloc(unsigned int);

Don't do that; use #include <stdlib.h> because that will be correct and what you wrote is typically incorrect (the argument to malloc() is a size_t, which is not necessarily an unsigned int; it might be unsigned long, or some other type).

struct Box {
    int x, y ,w, h;
};

Apart from erratic space, struct Box is OK.

struct Wall {
    char color[15];
    struct Box *boxes[20];
};

And struct Wall is OK too.

int main(int argc, const char *argv[])

You aren't using argc or argv, so you'd be better using the alternative declaration of:

int main(void)

Original code again:

{
    struct Wall *mywall = malloc(sizeof(struct Wall));

This allocates but does not initialize a single struct Wall. Of itself, it is OK, though you should check that the allocation succeeded before you use it. You also need to worry about allocating the struct Box items that the elements of the array will point to.

    struct Box *myboxes[] = mywall->boxes;

You've got a minor catastrophe on hand here. You can't copy arrays like that. You haven't checked that you've got an array. Ignoring the error checking, you are stuck with one of:

    struct Box *myboxes[] = { &mywall->boxes[0], &mywall->boxes[1], ... };

or:

    struct Box **myboxes = &mywall->boxes;

I'm not convinced that you'd want the second version, for all it's shorter.

    return 0;

I like to see return 0; at the end of main(), even though C99 allows you to omit it.

}
like image 147
Jonathan Leffler Avatar answered Nov 19 '22 03:11

Jonathan Leffler