Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array initialisation in C

I know this is an old chestnut, but I want a small 2D array statically allocated in my code. I know the way to do this is:

static int A[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

That's fine and I can access all the members of it. However I have several problems passing it to a function, e.g.:

void print_matrix(int **a, int r, int c)
{
    int x, y;

    for(x = 0; x < r; x++)
    {
        printf("Row %02d = %#x = ", x, a[x]);

        for(y = 0; y < c; y++)
        {
            printf("%s%d", (0 == y) ? "" : ", ", a[x][y]);
        }
        printf("\n");
    }
}

Firstly I can't simply pass A to the function, I need to cast it to (int **). Since char * is synonymous to char [], I was a little surprised at this. Secondly, it crashes and when I check in the debugger, within the sub-function, a[0] is reported as 1 and not a pointer to an array of integers.

I know there is compiler/C language arcane magic happening here. But it is all a little confusing. If I try to initialise as:

static int *A[3] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };

I get a ton of warnings. How does this differ to:

static char *S[3] = { "hello", "there", "stackoverflow" };

Apart from the question of arcane C magic, which somehow I have never learnt despite over a decade of C programming :(, I would like to know how to generate my array so I can successfully pass it as an int ** without having to go through all the fag of for loops or copying the statically allocated array to a dynamically allocated one.

Would the following work?

int *A0 = { 1, 2 };
int *A1 = { 3, 4 };
int *A2 = { 5, 6 };
int **A = { A0, A1, A2 };

Is there a nicer way than this of doing it?

Thanks, all.

P.s. I know that in real life we would read values from a DB or file into dynamically allocated arrays and avoid all this stuff.

like image 283
AlastairG Avatar asked Dec 10 '10 14:12

AlastairG


1 Answers

A multidimensional array does not become a multi-level pointer (I don't know the proper term). Only one dimension decays. For example:

int [20] becomes int *; int [20][5] becomes int (*)[5] (which is not int **); etc.

If there is a great desire to use multidimensional arrays (via the [r][c] syntax), then you have to pass the other bounds (which must be constants). If variable bounds are needed, I think the best option is to perform the index conversion manually (i.e. instead of a[r][c], use a[r*C + c]).

like image 87
lijie Avatar answered Oct 05 '22 16:10

lijie