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.
Ouch; there are a number of problems here.
Don’t do that; use
#include <stdlib.h>because that will be correct and what you wrote is typically incorrect (the argument tomalloc()is asize_t, which is not necessarily anunsigned int; it might beunsigned long, or some other type).Apart from erratic space,
struct Boxis OK.And
struct Wallis OK too.You aren’t using
argcorargv, so you’d be better using the alternative declaration of:Original code again:
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 thestruct Boxitems that the elements of the array will point to.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:
or:
I’m not convinced that you’d want the second version, for all it’s shorter.
I like to see
return 0;at the end ofmain(), even though C99 allows you to omit it.