简体   繁体   中英

Why is not the last column of my matrix printed?

I have a 2x3 char matrix stored in column major order (yes I know that this is a little confusing, but please bear with me), as a multidimensional char[3][2] array (notice the switch of indices). Now, I want to print this matrix. However, for some reason the last column is not printed. Why is that?

Here's my code:

#include <stdio.h>

#define ARRAY_SIZE(x) ((sizeof (x)) / (sizeof((x)[0])))

typedef char matrix[3][2];

void print_matrix(matrix a)
{
    for (size_t i = 0; i < ARRAY_SIZE(a[0]); i++) {
        printf("[");
        for (size_t j = 0; j < ARRAY_SIZE(a); j++) {
            printf(" %c", a[j][i]);
        }   
        printf(" ]\n");
    }
}

int main(int argc, char *argv[])
{
    matrix a = {{'a','b'},{'c','d'},{'e','f'}};
    printf("sizeof(a) = %zu\n", ARRAY_SIZE(a));
    printf("sizeof(a[0]) = %zu\n", ARRAY_SIZE(a[0]));
    print_matrix(a);
    return 0;
}

Compiling and running gives me this:

$ gcc -Wall -std=c99 foo.c; ./a.out
sizeof(a) = 3
sizeof(a[0]) = 2
[ a c ]
[ b d ]

Expected output:

[ a c e ]
[ b d f ]

It's because your function is effectively:

void print_matrix(char a[3][2])

but this is really:

void print_matrix(char (*a)[2])

So your macro produces the wrong result using sizeof (you're calculating the size of a pointer, and the size of a two element char array). If you pass in the two values to the function as parameters and use those in the loop, it should work.

Add:

printf("ARRAY_SIZE(a) = %zu\n", ARRAY_SIZE(a));
printf("ARRAY_SIZE(a[0]) = %zu\n", ARRAY_SIZE(a[0]));

to print_matrix and you will see the problem:

ARRAY_SIZE(a) = 2
ARRAY_SIZE(a[0]) = 2

You have been bitten by one of the bizarre corner cases of C. Multidimensional arrays are not as fully supported as they seem to be. In particular, passing them as arguments to functions doesn't create quite the data type that you're expecting, and therefore the ARRAY_SIZE macro doesn't work properly on the function argument.

What's actually going on under the hood is weird, and I'm not sure I understand it well enough to really explain it, but the brief version is that arrays as function parameters degrade into pointers. So the function parameter char a[3][2] actually becomes something vaguely equivalent to char *a[2].

the sizeof operator doesn't work because arrays sent as parameters get converted to pointers and DECAYING of the pointer takes place! so inside the function you can't know the sizeof the matrix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM