我有一个搜索名称列表的函数,我试图让搜索函数将数组的索引返回给主函数并打印出找到的名称的起始位置。到目前为止,我尝试的所有操作要么使程序崩溃,要么导致奇怪的输出。
这是我的搜索功能:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX_NAMELENGTH 10
#define MAX_NAMES 5
void initialize(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys, int i);
int search(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys);
int main()
{
char names[MAX_NAMES][MAX_NAMELENGTH];
int i, Number_entrys,search_result,x;
printf("How many names would you like to enter to the list?\n");
scanf("%d",&Number_entrys);
initialize(names,Number_entrys,i);
search_result= search(names,Number_entrys);
if (search_result==-1){
printf("Found no names.\n");
}else
{
printf("%s",search_result);
}
getch();
return 0;
}
void initialize(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys,int i)
{
if(Number_entrys>MAX_NAMES){
printf("Please choose a smaller entry\n");
}else{
for (i=0; i<Number_entrys;i++){
scanf("%s",names[i]);
}
}
}
int search(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys)
{
int x;
char new_name[MAX_NAMELENGTH];
printf("Now enter a name in which you would like to search the list for\n");
scanf("%s",new_name);
for(x = 0; x < Number_entrys; x++) {
if ( strcmp( new_name, names[x] ) == 0 )
{
return x;
}
}
return -1;
}
就像我之前提到的那样,我尝试了很多不同的方法来尝试解决这个问题,但我似乎无法让它们发挥作用。像上面那样打印 X 只是我尝试的最后一件事,因此知道它不起作用。对最简单的方法有什么建议吗?