carraysmultidimensional-arrayhardcode

Is there way to hard code a two dimensional integer array without having to mention any dimension in C?


I can easily hard code 2D char arrays, avoiding specifying the last dimension, as below.

char *mobile_games[] = { "DISTRAINT", "BombSquad" }

Although, I can't do this...

char *pc_games[] = { { 'F', 'E', 'Z' }, { 'L', 'I', 'M', 'B', 'O' } }

The same warning pops up when I try something like...

int *rotation[] = { { 1, 0 }, { 0, 1 } }

I would like to know the exact reason as to why that happens, and how I can hardcode an int array by not having to mention the last dimension.


Solution

  • This isn't specific to 2D arrays. You can't initialize a pointer like this, either:

    int *int_array = {1, 2};
    

    The reason it works for strings is because string literals decay to pointers when used in that context. That's why you can use a string literal in the argument list of a function that takes a char * parameter.

    To do what you want, you need to declare it as a 2D array, rather than an array of pointers.

    int rotation[][2] = { { 1, 0 }, {0, 1} };
    

    If you really want an array of pointers, you will need to declare the row values separately.

    int rot0[] = {1, 0};
    int rot1[] = {0, 1};
    int *rotation[] = {rot0, rot1};