规则为C http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf如下:
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.
语言为C++ http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf有点不同:
4.2 Array-to-pointer conversion [conv.array]
1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue of type “pointer to T”. The result is a pointer to the first element of the array.
...
8.3.4 Arrays [dcl.array]
...
7 A consistent rule is followed for multidimensional arrays. If E is an n-dimensional array of rank i × j × ... × k, then E appearing in an expression is converted to a pointer to an (n−1)-dimensional array with rank j × ... × k. If the * operator, either explicitly or implicitly as a result of subscripting, is applied to this pointer, the result is the pointed-to (n−1)-dimensional array, which itself is immediately converted into a pointer.
因此,以下内容均成立:
Declaration Expression Type Decays to
----------- ---------- ---- ---------
T a[N] a T [N] T *
&a T (*)[N]
*a T
a[i] T
T a[M][N] a T [M][N] T (*)[N]
&a T (*)[M][N]
*a T [N] T *
a[i] T [N] T *
&a[i] T (*)[N]
*a[i] T
a[i][j] T
T a[M][N][O] a T [M][N][O] T (*)[M][N]
&a T (*)[M][N][O]
*a T [M][N] T (*)[N]
a[i] T [M][N] T (*)[N]
&a[i] T (*)[M][N]
*a[i] T [N] T *
a[i][j] T [N] T *
&a[i][j] T (*)[N]
*a[i][j] T
a[i][j][k] T
对于高维数组,该模式应该是清晰的。
那么让我们分析一下你的字典:
/* list of words and meanings */
char *dic[][40] = {
"atlas", "A volume of maps.",
"car", "A motorized vehicle.",
"telephone", "A communication device.",
"airplane", "A flying machine.",
"", "" /* null terminate the list */
};
这不会按照您想要的方式设置您的字典;您基本上已将其设置为包含 40 个 char 指针的 1 元素数组。如果您想要一个字符串对数组,则声明应如下所示:
char *dic[][2] =
{
{"atlas", "A volume of maps"},
{"car", "A motorized vehicle"},
{"telephone", "A communication device"},
{"airplane" , "A flying machine"},
{NULL, NULL} // empty strings and NULLs are different things.
};
的类型dic
是“指向 char 的指针的 2 元素数组的 5 元素数组”,或者char *[5][2]
。根据上述规则,表达式dic
应该衰减到char *(*)[2]
-- 指向 char 指针的 2 元素数组的指针。
搜索该字典的函数将如下所示:
char *definition(char *term, char *(*dictionary)[2]) // *NOT* char ***dictionary
{
while ((*dictionary)[0] != NULL && strcmp((*dictionary)[0], term) != 0)
dictionary++;
return (*dictionary)[1];
}
你可以从你的 main 函数中调用它,例如
char *def = definition(term, dic);
请注意,我们必须使用括号将*dictionary
函数中的表达式。数组下标运算符[]
优先级高于解引用运算符*
,并且我们不想添加下标dictionary
直接,我们想要将下标放入数组中dictionary
指着.