#include <Foundation/Foundation.h>
int lookup (const struct entry dictionary[],const char search[], const int entries);
struct entry
{
char word[15];
char definition[50];
};
struct entry dictionary[100] =
{
{ "aardvark", "a burrowing African mammal" },
{ "abyss", "a bottomless pit" },
{ "acumen", "mentally sharp; keen" },
{ "addle", "to become confused" },
{ "aerie", "a high nest" },
{ "affix", "to append; attach" },
{ "agar", "a jelly made from seaweed" },
{ "ahoy", "a nautical call of greeting" },
{ "aigrette", "an ornamental cluster of feathers" },
{ "ajar", "partially opened" }
};
int lookup (const struct entry dictionary[],const char search[],const int entries)
{
int i;
for ( i = 0; i < entries; ++i )
if ( strcmp(search, dictionary[i].word) == 0 )
return i;
return -1;
}
int main (void)
{
char word[10];
int entries = 10;
int entry;
printf ("Enter word: ");
scanf ("%14s", &word);
entry = lookup (dictionary, word, entries);
if ( entry != -1 )
printf ("%sn", dictionary[entry].definition);
else
printf ("The word %s is not in my dictionary.n", word);
return 0;
}
在此处输入图像描述
由于很多原因,您的代码是错误的。
首先,使用一个定义为
char word[10];
用
scanf ("%14s", &word);
大错特错。
你不需要传递数组变量的地址,数组名称衰减到指向第一个元素的指针。 使用
scanf()
,%s
期望参数作为指向字符数组开头的指针,足够长的时间以容纳转换后的输入和 null 终止符。对于大小为 10 的数组,它可以容纳大小为 9 的字符串(加上 null 终止符),您允许扫描和存储 14 个字符,这是无效的内存访问,会导致未定义的行为。
也就是说,您也没有检查scanf()
呼叫是否成功。如果scanf()
失败,您将访问不确定的值。
您应该在第一次使用它之前进行结构类型struct entry
的声明,该声明位于声明之前的原型中。