-1

Initialise a 2D array matrix as follows:

#define N 3
...
int matrix[N][N] = {};

The elements of the matrix can be accessed as follows:

for(i=0; i<N; ++i)
{
    for(j=0; j<N; ++j)
        printf("%d ", *(*(matrix + i) + j) );
    printf("\n");
}

However the following code fails with a segmentation fault.

int **matrix_pointer = (int **)matrix;
for(i=0; i<N; ++i)
{
    for(j=0; j<N; ++j)
        printf("%d ", *(*(matrix_pointer + i) + j) );
    printf("\n");
}

Please, Explain why or suggest an alternate method (with pointers) that works.

1 Answers1

0

If defining

int matrix[3][5];

add then putting just matrix to the right of an =-operator, the array matrix decays (as every array would do) to the address of it's 1st element.

matrix's 1st element is an int[5]. The address of an int[5] is int(*)[5].

To if "putting just matrix to the right of a =-operator" then the left side of this assignment operation is expect to be a int(*)[5]:

int (*row)[5] = matrix;

Understanding the above it is obvious that doing

int ** ppi = matrix 

cannot be correct as int ** is not the same as int(*)[5].

It assigns to a pointers from another pointer of different, will say incompatible type. The compiler would warn about this.

Apply a cast to the right hand side expression to fit the left hand side, is just telling the compiler to shut-up.

alk
  • 69,737
  • 10
  • 105
  • 255