Assigning data to array using curly brackets

14,149

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.

Share:
14,149

Related videos on Youtube

roger_rales
Author by

roger_rales

Updated on June 21, 2022

Comments

  • roger_rales
    roger_rales about 2 years

    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?

    • Marlon
      Marlon almost 13 years
      Not only is it wrong, you are going to cause a memory leak.
    • roger_rales
      roger_rales almost 13 years
      Can you elaborate on that, Marlon? Knowing it causes one won't help unless I know why...
    • Marlon
      Marlon almost 13 years
      Even though your code doesn't compile, it demonstrates how a real memory leak is caused. The address returned by malloc must be freed. Since you are are reassigning a different address to map, you lose the address returned by malloc and thus you can no longer free it.
  • roger_rales
    roger_rales almost 13 years
    Ah I see. Makes sense actually. I have seen a few pieces of code assigning map/pixel data in a similar way, so I thought it was possible, although after double-checking, I realized it's as you say.
  • trusktr
    trusktr almost 11 years
    @Kerrek, Can you do something like int x[] = {1,2,3,4,5,6} to make the array an arbitrary size when you assign the values (omitting the size between the square brackets)?
  • trusktr
    trusktr almost 11 years
    @KerrekSB oh, sweet. If you do int x[]; would x just be an int pointer not pointing to anything?