搜索功能可能返回双值

时间:2018-12-02 18:17:12

标签: c

我正在编写搜索功能。参数是:

(char *array, char to_find)

char search (char *array, char to_find)
{
int counter;
for (counter =0; array[counter]!='\0'; counter++)
{ if (to_find==array[counter])
  return 2; 
else return 0;
}
}

int main()
{
char *word[100]="woman";
char letter;
scanf("%c" &letter);
if (search(word, letter)==1)
{ 
printf("match")}

}

我想知道是否也可以修改此代码以返回2个值;如果为true,则返回1和计数器。例如,我尝试过:

    char search (char *array, char to_find)
    {
    int counter;
    for (counter =0; array[counter]!='\0'; counter++)
    { if (to_find==array[counter])
      return 2; 
    else return 0;

    }
    }
char searchindex(char *array, char to_find)
{ int counter;
for (counter=0; array[counter]!='\0'; counter++)
{
if (to_find==array[counter])
{
return counter;
}
else return -1;
}



int main()
    {
    char *word[100]="woman";
    char letter;
    int position;
    scanf("%c" &letter);

    /**I tried representing the return values as integers**/
int test1= search(word, letter);
int test2= searchindex(word, letter);
if ((test1+test2)>0) 
{printf(match);} /**this had errors but i can't seem to find them**/
    }

1 个答案:

答案 0 :(得分:1)

首先请注意,您的if-else语句似乎很奇怪。你有:

char search (char *array, char to_find)
{
    int counter;
    for (counter =0; array[counter]!='\0'; counter++)
    { 
        if (to_find==array[counter])
            return 2; 
        else return 0;  // This strange....
    }

}

这意味着您将始终在第一次比较后返回。您可能想要:

char search (char *array, char to_find)
{
    int counter;
    for (counter =0; array[counter]!='\0'; counter++)
    { 
        if (to_find==array[counter])
            return 2; 
    }
    return 0;
}

然后您问:

  

…可以修改此代码以返回2个值

否,在C语言中只能直接返回一个值。但是,有多种方法可以“返回”多个值。

例如,将指针传递给变量,然后使用指针更改值。喜欢:

char search (char *array, char to_find, int* counter)
{
    for (*counter = 0; array[*counter]!='\0'; (*counter)++)
    { 
        if (to_find==array[*counter])
            return 2; 
    }    
    return 0;
}

// Call it like
int counter;
int test1= search(word, letter, &counter);

另一种方法是制作一个结构并返回该结构。喜欢:

struct X {
    int result;
    int counter;
};

struct X search (char *array, char to_find)
{
    struct X res;
    for (res.counter = 0; array[res.counter]!='\0'; res.counter++)
    { 
        if (to_find==array[res.counter])
        {
            res.result = 2;
            return res;
        } 
    }    
    res.result = 0;
    return res;
}

// Call it like
struct X test1= search(word, letter, &counter);