开发者

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.


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]).


The quickest way is to declare argument a as int a[][2].

void print_matrix(int[][2] a, int r, int c);

// and call the function like this:
print_matrix(A, 3, 2);


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

You were close with the last section, but need slightly different declarations. The resulting A can be passed as an int ** to a function.

With this, print_matrix(A, 3, 2); outputs:

Row 00 = 0x5eaeda70 = 1, 2
Row 01 = 0x5eaeda68 = 3, 4
Row 02 = 0x5eaeda60 = 5, 6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜