Ad

How To Make A Pointer To An Array Of String In C?

- 1 answer

I want to make a pointer to an array of string(matrix[10][10]), but I get "initialization from incompatible pointer type" problem so how to fix it? And what is the problem?

void rotate(char matrix[10][10]){
  
  char * pMatrix = matrix;
  for(int j = 0; j < 10; j ++){
    for(int i = 9; i >= 0; i --){
      *pMatrix = matrix[i][j];
      pMatrix ++;
    }
  }

}

btw, my task is to perform 90 degree clockwise rotation of matrix, but my algorithm is terrible I know

Ad

Answer

matrix is of type char (*)[10] (pointer to array of 10 char).

pMatrix is of type char * (pointer to char).

There is a type mismatch when you use:

char *pMatrix = matrix;

You try to assign a pointer to an array of 10char to a pointer to char.

This is why you get the warning:

warning: initialization of 'char *' from incompatible pointer type 'char (*)[10]'


You need to dereference matrix

char *pMatrix = *matrix;

to get a pointer to char.

Could you say why my version (char * pMatrix = matrix;) works for 1D array, but stops working for 2d array?

matrix' type is different when declared as char matrix[10] and parameter of a function. Then matrix is actual equivalent to char *. The assignment from char * to char * is correct.

Take a look at:

Note that if you provide an amount of elements like in your case doesn't matter. char matrix[10] is equal to char matrix[] which is furthermore equal to char *matrix.


No guarantee if your algorithm works beside that. If you got problems with that, please ask a different question.

Ad
source: stackoverflow.com
Ad