Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning data to array using curly brackets

Tags:

arrays

c

malloc

In the C language, why does the following expression fail?

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 data in such a "row/column" format into a C array. However, the compiler fails with

error: expected expression before ‘{’ token

(in the map = { line). Filling the array in other ways works fine, and I am sure the brackets work for initializations...I can't do that after I have allocated memory?

EDIT: I solved it by making a temporary char array and then feeding the data to the malloced map in a for loop. Still. I'd like to know why the above code would leak memory as pointed below. And would my fix (parsing the temp array and setting the map data with it) leak memory as well?

like image 899
roger_rales Avatar asked Jul 23 '11 23:07

roger_rales


1 Answers

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

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

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

Here is the closest construct that would 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 of the brace-list must itself initialize the base type of the aggregate.

like image 131
Kerrek SB Avatar answered Oct 12 '22 21:10

Kerrek SB