Multidimensional array and pointer to pointers

When you create a multidimensional array char a[10][10] , according to my book, you should use a parameter similar to char a[][10] to pass an array to a function.

Why should you indicate the length as such? Aren't you just passing a double pointer to what's with it, and isn't this double pointer pointing to allocated memory? So why can't the parameter be char **a ? Do you reallocate the new memory by supplying a second 10.

+6
c arrays pointers pointer-to-pointer
source share
2 answers

Pointers are not arrays

A dereferenced char ** is an object of type char * .

The dereferenced char (*)[10] is an object of type char [10] .

Arrays are not pointers

See the c-faq entry for this very subject .


Suppose you have

 char **pp; char (*pa)[10]; 

and, for the sake of argument, both point to the same place: 0x420000.

 pp == 0x420000; /* true */ (pp + 1) == 0x420000 + sizeof(char*); /* true */ pa == 0x420000; /* true */ (pa + 1) == 0x420000 + sizeof(char[10]); /* true */ (pp + 1) != (pa + 1) /* true (very very likely true) */ 

and therefore, the argument cannot be of type char** . In addition, char** and char (*)[10] are not compatible types, therefore argument types (decomposed array) must match the parameters (type in the function prototype)

+12
source share

C language standard, draft n1256 :

6.3.2.1 Lvalues, arrays, and function notation
...
3 Unless it is an operand of the sizeof operator or a unary operator & , or a string literal used to initialize an array, an expression that is of type `` array type is a pointer to type that is converted to an expression with type '', which indicates the initial element is an array object and is not an lvalue value. If the array object has a register storage class, the behavior is undefined.

Given an announcement

 char a[10][10]; 

array expression type a is "10 element array of 10 element char array". The rule above, which closes to enter a "pointer to a 10-element array char " or char (*)[10] .

Remember that in the context of declaring a parameter, the functions T a[N] and T a[] identical to T *a ; thus, T a[][10] is identical to T (*a)[10] .

+1
source share

All Articles