在C中返回并打印字符串数组索引

时间:2012-10-30 20:59:48

标签: c printing indexing

我有一个搜索名称列表的函数,我试图让搜索函数将数组的索引返回给main函数,并打印出找到的名称的起始位置。到目前为止,我所尝试的所有内容都会导致程序崩溃或导致奇怪的输出。

这是我的搜索功能:

#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只是我尝试的最后一件事,因此知道它不起作用。有关最简单方法的任何建议吗?

1 个答案:

答案 0 :(得分:0)

为什么不使用strcmp而不是strstr?

在您的代码中,似乎存在一些巨大的问题: - 似乎我没有初始化。 - 你将x声明为int然后使用:printf(“%s”,x)这里有点无意义。顺便说一句,不是initiliaze!

这样的东西应该更好(请注意我没有你的初始化函数)并且我没有尝试编译:

int search(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys)
{
   int x =0;
   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;        
 }

主要:

int main()
{
    char names[MAX_NAMES][MAX_NAMELENGTH];
    int i=0;
    int Number_entrys=0;
    int search_result=0;
    printf("How many names would you like to enter to the list?\n");
    scanf("%d",&Number_entrys);
    initialize(names,Number_entrys,i); // I guess it is use to initialize names ?!?
    search_result= search(names,Number_entrys);
    if (search_result==-1)
    {
         printf("Found no names.\n");
    }
    else
    {
       printf("Index found in position %d in the tab\n",search_result);
    }
   getch(); //not really a fan of this...
   return 0;
 }

希望它有所帮助。

此致

JOZE