简体   繁体   中英

why i get segment error when i print 2-D array which is delivery by the "main" function

why I get segment error when I print 2-D array which is delivery by the "main" function?There is a condition that the array must be delivery as int** 。how can I do that?

#include <stdio.h>

void display_matrix(int** matrix, int row, int column) {
    printf("%d\n", matrix[1][2]);
}

void main() {
    int m[3][4] = {
        {1, 3, 5, 7},
        {10, 11, 16, 20},
        {23, 30, 34, 60}
    };
    display_matrix((int**) m, 3, 4);
}

You are getting Segmentation Fault because you are passing an array of integers to where an array of pointers is expected.

You have to prepare an array of int* .

#include <stdio.h>

void display_matrix(int** matrix, int row, int column) {
    printf("%d\n", matrix[1][2]);
}

int main(void) {
    int m[3][4] = {
        {1, 3, 5, 7},
        {10, 11, 16, 20},
        {23, 30, 34, 60}
    };
    int* m_ptr[3] = {m[0], m[1], m[2]};
    display_matrix(m_ptr, 3, 4);
}

For starters according to the C Standard the function main without parameters shall be declared like

int main( void )

An array declared like

int m[3][4] = {
    {1, 3, 5, 7},
    {10, 11, 16, 20},
    {23, 30, 34, 60}
};

used in expressions with rare exceptions is converted to a pointer to its first element of the type int ( * )[4] .

So the types int ( * )[4] and the type int ** are not compatible. Dereferencing the pointer of the type int ** for the declared array above you will get the value 1 that is not a valid address. So the function invokes undefined behavior.

Thus a function that accepts such an array as an argument should be declared like

void display_matrix( int ( *matrix )[4], size_t rows );

and the function can be called like

display_matrix( m, 3 );

Or if your compiler supports variable length arrays then the function can be declared like

void display_matrix( size_t rows, size_t cols, int ( *matrix )[cols] );

and the function can be called like

display_matrix( 3, 4, m );

Such a declaration of a function

void display_matrix(int** matrix, int row, int column);

usually is used when you allocated arrays dynamically like

int **m = malloc( 3 * sizeof( int * ) );
for ( size_t i = 0; i < 3; i++ )
{
    m[i] = malloc( 4 * sizeof( int ) );
}

//... initialization of the arrays and


display_matrix( m, 3, 4 );

So either define the array dynamically or use one more array declared like

int * a[3] = { m[0], m[1], m[2] };

and pass this array instead of the array m to your function.

In this case the array a used as an argument expression in this call

display_matrix( a, 3, 4 );

will be implicitly converted to a pointer of the type int ** .

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