1

I was searching about pointers in C, and I found this question. Basically, the user wants to know how to pass a matrix as a argument of a function in C. The most voted answer says that he can't use a pointer to pointer (type ** identifier) because:

(...) any static 2D array requires that second level of pointers be const pointer to static array

What he does mean when he says "const pointer to static array"? And how this is coded? I know what const variables (included pointers) does mean, so as static variables too. But, in this case, why it does have to be const pointer to a static array?

Community
  • 1
  • 1
José Joaquim
  • 103
  • 2
  • 9
  • The text you quote makes no sense. Looks like the guy that wrote it has deleted his account too – M.M Apr 06 '17 at 04:58
  • 2
    Basically declaring `int array[x][y];` (where `x` and `y` are constants), you are declaring a type `int [x][y]`. When passing as an parameter to a function, the first level of indirection is converted to a pointer. That means it will be passed as `int (*)[y]` which is **not the same** as `int **`. `int **` is a **pointer-to-pointer-to-int**, `int (*)[y]` is a **pointer-to-array-of-int** `[y]` (ints big each). – David C. Rankin Apr 06 '17 at 05:04
  • "Static" in this case probably means "opposite of dynamic". The pointer-to-pointer syntax is not a 2D array and most of the time it is also bad practice. See [Correctly allocating multi-dimensional arrays](http://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). – Lundin Apr 06 '17 at 06:56

1 Answers1

1

What he does mean when he says "const pointer to static array"?

I think he meant to say that the array needs to be treated as though it's contiguous; it needs to be a sequence of elements one after the other with no room for pointers. He might be trying to claim that dereferencing a two-dimensional array once (e.g. *mat or mat[0]) should result in a constant that points at the sub-array (which is also incorrect in certain situations, one of which I'll cover soon, when used as the operand of sizeof).

FWIW, this is also incorrect:

The previous header would be correct if the matrix is dynamic array.

int mat[SIZE][SIZE]; If we inspect this object, sizeof mat is equal to sizeof (int) * SIZE * SIZE; there's no room for any pointer storage within this matrix. However, in void ins (int **matrix, int row, int column);, int **matrix tells us that matrix points at int *, which implies that there is room for pointers, and also implies that matrix might not be contiguous.

... how this is coded?

Incorrectly, for that question, as int ** points at int * objects, not at int[SIZE] objects.

... why it does have to be const pointer to a static array?

See the first paragraph of this answer.

autistic
  • 1
  • 3
  • 35
  • 80