【发布时间】:2011-04-24 15:48:46
【问题描述】:
我将多维数组理解为指向指针的指针,但也许我错了?
例如,我认为:
char * var = char var[]
char ** var = char* var[] 或 char var[][]
char *** var = char var[][][] 或 char* var[][] 或 char** var[]
这是不正确的吗?我很困惑,因为我在一个简单的教科书示例中看到一个 char*[][] 转换为 char**。
我粘贴了下面的示例。谁能帮我解决这个问题?谢谢!
/* A simple dictionary. */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* 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 */
};
int main(void)
{
char word[80], ch;
char **p;
do {
puts("\nEnter word: ");
scanf("%s", word);
p = (char **)dic;
/* find matching word and print its meaning */
do {
if(!strcmp(*p, word)) {
puts("Meaning:");
puts(*(p+1));
break;
}
if(!strcmp(*p, word)) break;
p = p + 2; /* advance through the list */
} while(*p);
if(!*p) puts("Word not in dictionary.");
printf("Another? (y/n): ");
scanf(" %c%*c", &ch);
} while(toupper(ch) != 'N');
return 0;
}
【问题讨论】:
-
请注意,在这种特定情况下,在 C++ 中,最好使用
std::map而不是这里的。 -
上面的代码来自 Herbert Schildt 在 C 中的完整参考 页码 212 但我不明白 if(!strcmp(*p, word)) break; 我认为那句话是多余的。因为如果单词与 *p 处的当前元素匹配,那么它应该已经导致内部 do while 中断。请就此问题赐教
标签: c++ c arrays pointers multidimensional-array