尝试下一个:
(详细内容请阅读评论,并测试其如何工作的)
#include <stdio.h>
#include <assert.h>
/*
Return index an integer number begin from start an array,
otherwise return -1.
*/
int indexOf(int *array, int array_size, int number) {
for (int i = 0; i < array_size; ++i) {
if (array[i] == number) {
return i;
}
}
return -1;
}
// Tests for indexOf()
void test_indexOf() {
int array[10] = {12, 78, -43, 0, 21, 12, 20, -9, 1, -1};
assert(indexOf(array, 10, 12) == 0);
assert(indexOf(array, 10, 0) == 3);
assert(indexOf(array, 10, 2) == -1);
assert(indexOf(array, 10, 43) == -1);
assert(indexOf(array, 10, 11) == -1);
assert(indexOf(array, 10, -1) == 9);
assert(indexOf(array, 10, 1) == 8);
assert(indexOf(array, 10, -2) == -1);
assert(indexOf(array, 10, 3) == -1);
}
int main() {
test_indexOf();
return 0;
}
注:
由于C还没有支持重载函数,indexOf()只能和inte数组类型一起工作蒙古包。
的C已不适合的阵列的指针的定长支持。所以,你需要手动传递数组的大小。
测试环境:
-
$ uname -a
Linux wlysenko-Aspire 3.13.0-37-generiC#64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
$ gcc --version
gcc (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5
谢谢你,在我的情况,我认为是最好的解决办法。我的阵列很短,我必须在很多时间搜索它。每次分类和搜索都不会大大改善时间。非常感谢。 – 2013-02-27 10:52:45