Array of structure pointers, invalid initialization 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 an invalid initializer error on line 14. What I'm trying to do is get a copy of an array of pointers to a structure that are in a different structure.

+4
source share
2 answers

Ai; there are a few problems here.

 extern void *malloc(unsigned int); 

Do not do that; use #include <stdlib.h> because it will be correct, and what you wrote is usually incorrect (the malloc() argument is size_t , which is not necessarily an unsigned int , it can be an unsigned long or some or another type).

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

Besides the unstable space, the struct Box is fine.

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

And struct Wall is OK too.

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

You are not using argc or argv , so you better use an alternative declaration:

 int main(void) 

Original code again:

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

This highlights, but does not initialize, one struct Wall . This in itself is normal, although you must make sure that the selection is done before using it. You also need to worry about the distribution of the struct Box elements that the array elements point to.

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

You have a small disaster here. You cannot copy such arrays. You have not noted that you have an array. Ignoring error checking, you are stuck in one of:

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

or

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

I'm not sure that you will need the second version, as all this will be shorter.

  return 0; 

I like to see return 0; at the end of main() , although C99 allows it to be omitted.

 } 
+5
source

What about:

 struct Box **myboxes = mywall->boxes; 

?

Then you can do things like:

  for ( int i = 0 ; i < 15 ; i++ ) mywall->boxes[i] = malloc(sizeof(Box)); Box* x = myboxes[1]; 

Since the code is now, mywall->boxes not initialized.

NOTE: just re-read the question - this will not return a copy of the array, but points to the same place. There is no short copy solution without using memcpy or just copying structures.

0
source

Source: https://habr.com/ru/post/1401450/


All Articles