简体   繁体   中英

Dereferencing pointer to a pointer doesn't work when I pass it to a function. Why? (C)

I tried everything I could think off. I don't know if I'm missing something obvious. Why does this work:

#include<stdio.h>

void test_matrix(int** matrix)
{
    for(int i=0; i<4; i++) {
        for(int j=0; j<4; j++) {
            printf("%d ", *(matrix+j+4*i));
        }
    }
    /**
    for(int i=0; i<4; i++) {
        for(int j=0; j<4; j++) {
            printf("%d ", *(*(matrix+i)+j));
        }
    }
    */
}
int main()
{
    int matrix[4][4];
    for(int i=0; i<4; i++)
        for(int j=0; j<4; j++)
            scanf("%d", &matrix[i][j]);
    test_matrix(matrix);
}

But the commented section doesn't work. I also tried matrix[i][j] and it still won't work. My program times out. EDIT: I added the function calling in MAIN.

The error is that this 2D-array is laid out as 4 x 4 = 16 integers. But your function expects a pointer to pointers.

It's right that at the calling site the address of matrix is provided as the argument. But unlike some commenter said, it's not a pointer to int but a pointer to an int -array.

To handle this address of the 2D-array correctly you need to tell it your function, like this:

void test_matrix(int (*matrix)[4])
{
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            printf("%d ", *(*(matrix + i) + j));
        }
    }
}

or like this:

void test_matrix(int matrix[][4])
{
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            printf("%d ", matrix[i][j]);
        }
    }
}

Which kind of access you use doesn't matter, sometimes it's just a matter of taste. These expressions are equivalent, actually p[i] is syntactic sugar for *(p + i) :

*(*(matrix + i) + j)

matrix[i][j]

Note 1: As some commenters already recommend, you should raise the warning level to the maximum and correct the source until all diagnostics are handled.

Note 2: When your arrays vary in their dimensional sizes you need to think of a way to tell these sizes to your function.

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