Assigning data to an array using curly braces

In C, why does the following expression not work?

map = malloc(sizeof(Map) * tiles); map = { 0,2,0,0,0,0,0,0,2,0, 0,1,0,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 2,1,0,0,0,0,0,0,1,2, 0,0,0,0,0,0,0,0,0,0 }; 

I just want to fill the data in this row / column format into an array C. However, the compiler does not work with

 error: expected expression before '{' token 

(in map = {line). Filling the array with other methods works fine, and I'm sure the brackets work for initialization ... Can't I do this after I have allocated the memory?

EDIT: I solved this by creating a temporary char array and then feeding the data to the malloced card in a for loop. Still. I would like to know why the above code will be a memory leak, as indicated below. And will there be my correction (parsing the tempo array and setting the card data with it)?)

+6
source share
1 answer

Your Map * map; is a pointer, not an array. Rocker braces for aggregate initialization:

 int x[3] = { 1, 2, 3 }; 

Pointers are not arrays, and you cannot fill memory with aggregate initialization syntax.

Here is the closest construct that will work:

 typedef struct Map_ { int a; int b; } Map; // some struct Map m[] = { {1,2}, {3,4}, {5,6} }; /* we initialized "Map m[3]", it has automatic storage! */ 

Note that each element in the list of figures must itself initialize the basic type of aggregate.

+9
source

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


All Articles