Multi-dimensional array and pointer to pointers

半腔热情 提交于 2019-12-05 08:42:54

Pointers are not arrays

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

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

Arrays are not pointers

See the c-faq entry about this very subject.


Assume 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 this is why the argument cannot be of type char**. Also char** and char (*)[10] are not compatible types, so the types of arguments (the decayed array) must match the parameters (the type in the function prototype)

C language standard, draft n1256:

6.3.2.1 Lvalues, arrays, and function designators
...
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

Given a declaration of

char a[10][10];

the type of the array expression a is "10-element array of 10-element array of char". Per the rule above, that gets coverted to type "pointer to 10-element array of char", or char (*)[10].

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!