指数值不会改变

Bob*_*bby 0 c arrays

我正在尝试实现线性搜索功能来搜索用户"输入"的特定数字,例如用户想要搜索给定数组中的数字3.该函数应返回索引值2.但无论输入什么输入,我的代码都返回6.我怀疑我的main函数有问题(可能在我使用for循环时,i的值固定为6?).有任何想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


#define numberOfElements 6
#define NOT_FOUND -1

int linearSearch (int *myArray, int key, int i);

int main (int argc, char *argv[]){

   int i, key, myArray[] = {1, 2, 3, 4, 5, 6};
   printf("Input: ");
   for (i = 0; i < numberOfElements; i++){
      printf("%d ", myArray[i]);
   }
   printf("\n");
   printf("Please enter a number you wish to search for: ");
   scanf("%d", &key);
   linearSearch (myArray, key, i);
   printf("The number %d is at index %d\n", key, i);

   return 0;
} 


int linearSearch (int *myArray, int key, int i) {

   for (i = 0; i < numberOfElements; i++){
      printf("Checking index %d\n", i);
      if (myArray[i] == key){
         printf("%d\n", i);
         return i;
         break;
      }
      printf("It's certainly not here!\n");
   }

   return NOT_FOUND;
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*ris 5

您忽略linearSearch函数的返回值.因此,您不打印答案.

请注意,您不应该传入i函数,而是在循环中声明它:

for (int i=0; i<... etc
Run Code Online (Sandbox Code Playgroud)