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.