Initializing a 2D Array in C

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

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

This is great, and I can access all its members. However, I have a few problems passing its functions, for example:

 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 just pass A function, I need to pass it (int **). Since char * is synonymous with char [] , I was a little surprised by this. Secondly, it crashes, and when I check the debugger, in a subfunction, a[0] reported as 1 , not a pointer to an array of integers.

I know that there is the secret magic of the / C compiler. But all this is a bit confusing. If I try to initialize as:

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

I get a ton of warnings. How is this different from:

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

Besides the question about C secret magic, which I still did not recognize, despite more than a decade of programming in C :(, I would like to know how to generate my array so that I can successfully pass it as int ** without having to go through the whole fag for loops or copy a statically allocated array to a dynamically allocated one.

Will there be a next job?

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

Is there a better way to do this?

Thank you all.

Ps I know that in real life we ​​will read values ​​from a database or file into dynamically distributed arrays and avoid all this.

+4
source share
5 answers

A multidimensional array does not become a layered pointer (I don't know the correct term). Only one dimension breaks up. For instance:

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

If there is a great desire to use multidimensional arrays (via the syntax [r][c] ), then you need to pass other bounds (which should be constants). If variable constraints are needed, I think the best option is to do the index conversion manually (ie Instead of a[r][c] , use a[r*C + c] ).

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

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

At the same time print_matrix(A, 3, 2); produces:

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

The fastest way is to declare the 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); 
+1
source
 static char *S[3] = { "hello". "there", "stackoverflow" }; // ^~~~~~ This is a period. 
0
source

All Articles