这个字符串怎么可以运行?
How can this string run?
这是本程序中的电子词典program.But,dict[i][0]如何与space.And进行比较true.And如何在最后的if部分dict[i][0] 与 space.Please 比较谁能解释一下。
#include<stdio.h>
#include<string.h>
int main(void)
{
char dict[][2][40] = {
"house","a place of dwelling",
"car","a vehicle",
"computer","a thinking machine",
"program","a sequence of instruction",
"",""
};
char word[80];
int i;
printf("Enter word: ");
gets(word);
i = 0;
while(strcmp(dict[i][0], "")){
if(!strcmp(word, dict[i][0])){
printf("Meaning: %s", dict[i][1]);
break;
}
i++;
}
if(!strcmp(dict[i][0], ""))
printf("Not in dictionary\n");
return 0;
}
在您的代码中,
strcmp(dict[i][0], "")
不比较 dict[i][0]
和 ) space,而是检查 空 字符串,是定义数组的标记值。
另请注意,dict[i][0]
的类型是 char[40]
,它会衰减为 char *
,因此无论如何这是 strcmp()
的有效参数。
最好把get(word);
改成scanf("%s", word);
,因为它已经过时了,而且有缓冲区溢出问题。此外,""
表示空字符串而不是 space。基本上,space 使用 ' '
、'\r'
或 '\t'
字符之一显示。
回到你的问题,C 中的数组被转换为该类型的指针,因此 dict[][2][40] 是一个 3D 数组,但基本上是一个大小为 2x40 的 2D 数组,这意味着该数组的每个条目是一个大小为 40 的指针。
因此,您可以使用指针算法重写代码,将 dict[0]
的起始地址放入 *j
指针并将其增加 40 x 40 以提取 key 的 特定值 和 80 x 80 到达 下一个键 .
char *j = dict[0];
while(strcmp(j, "")){
if(!strcmp(word, j)){
j = j + 40;
printf("Meaning: %s\n", j);
break;
}
j = j + 80;
}
if(!strcmp(j, ""))
printf("Not in dictionary\n");
这是本程序中的电子词典program.But,dict[i][0]如何与space.And进行比较true.And如何在最后的if部分dict[i][0] 与 space.Please 比较谁能解释一下。
#include<stdio.h>
#include<string.h>
int main(void)
{
char dict[][2][40] = {
"house","a place of dwelling",
"car","a vehicle",
"computer","a thinking machine",
"program","a sequence of instruction",
"",""
};
char word[80];
int i;
printf("Enter word: ");
gets(word);
i = 0;
while(strcmp(dict[i][0], "")){
if(!strcmp(word, dict[i][0])){
printf("Meaning: %s", dict[i][1]);
break;
}
i++;
}
if(!strcmp(dict[i][0], ""))
printf("Not in dictionary\n");
return 0;
}
在您的代码中,
strcmp(dict[i][0], "")
不比较 dict[i][0]
和 ) space,而是检查 空 字符串,是定义数组的标记值。
另请注意,dict[i][0]
的类型是 char[40]
,它会衰减为 char *
,因此无论如何这是 strcmp()
的有效参数。
最好把get(word);
改成scanf("%s", word);
,因为它已经过时了,而且有缓冲区溢出问题。此外,""
表示空字符串而不是 space。基本上,space 使用 ' '
、'\r'
或 '\t'
字符之一显示。
回到你的问题,C 中的数组被转换为该类型的指针,因此 dict[][2][40] 是一个 3D 数组,但基本上是一个大小为 2x40 的 2D 数组,这意味着该数组的每个条目是一个大小为 40 的指针。
因此,您可以使用指针算法重写代码,将 dict[0]
的起始地址放入 *j
指针并将其增加 40 x 40 以提取 key 的 特定值 和 80 x 80 到达 下一个键 .
char *j = dict[0];
while(strcmp(j, "")){
if(!strcmp(word, j)){
j = j + 40;
printf("Meaning: %s\n", j);
break;
}
j = j + 80;
}
if(!strcmp(j, ""))
printf("Not in dictionary\n");