我创建了一个程序,它接受字符串并将它们存储在一个二维数组中。它还有一个函数,用于搜索数组中的字符串(由用户输入)。但是每当我运行程序时,它会在到达搜索部分时停止工作。有谁可以指出我的错误?
这是我的代码
#include <stdio.h>
#include <string.h>
#define maxname 40
#define maxlength 70
int acceptSize()
{
int sizeOf;
printf("How many students?");
scanf("%d",&sizeOf);
return sizeOf;
}
void acceptNames(char names[maxname][maxlength],int size)
{
int ctr;
for(ctr=0; ctr<size; ctr++)
{
printf("Student %d:", ctr+1);
scanf("%s",&names[ctr]);
}
}
int searchName(char names[maxname][maxlength], char sname[maxname]){
int ctr2;
for(ctr2=0; ctr2<maxname; ctr2++)
{
if(strcmp(names[ctr2], sname[maxname])==0)
{
return ctr2;
}
}
return -1;
}
int main(){
int ctr,size, choice, result;
char names[maxname][maxlength], sname[maxlength];
size=acceptSize();
acceptNames(names,size);
printf("Enter name to be searched: ");
scanf("%s", &sname[maxlength]);
result=searchName(names, sname);
if(result == -1)
printf("Match is not found.");
else
printf("Match is found!");
}
答案 0 :(得分:3)
char sname[maxname] // in int searchName()
应该是
char sname[]; // See comment#1 by weather-vane
另外
if(strcmp(names[ctr2], sname[maxname])==0)
应该是
if(strcmp(names[ctr2], sname)==0) // sname[maxname] is not a string, sname is !!
最后
scanf("%s", &sname[maxlength]);
已经
了scanf("%s", sname); // reading a string is a case where you could omit &
建议:使用[ fgets ]代替scanf
使用