2
我在編寫的二進制搜索中返回值存在問題。在C中返回值
我有以下:
INT的binarySearch(字符*指令[],INT低,INT高,字符*串);
int main() {
char *instructions[]; // some array of strings - it does not include the string "jk"
char *string = "jk";
int high = inst_len;
int x = binarySearch(instructions, 0, high, string);
if (x == -1)
printf("not found");
else if (x == -2)
printf("error");
else
printf("Found at %d", x);
}
int binarySearch(char *instructions[], int low, int high, char *string) {
int mid = low + (high - low)/2;
// Not found
if (high <= low)
return -1;
// If instructions[mid] is less than string
else if (strcmp(instructions[mid], string) > 0)
binarySearch(instructions, low, mid-1, string);
// If instructions[mid] is larger than string
else if (strcmp(instructions[mid], string) < 0)
binarySearch(instructions, mid+1, high, string);
// Return position
else
return mid;
}
無論怎樣,在main
,的binarySearch總是返回0。但是,當我把打印語句的二進制搜索算法,我得到的返回-1
。這是爲什麼發生?這很奇怪!
順便說一句:如果你在你的編譯器打開了警告,它應該告訴你,這個函數並不總是返回值。如果您沒有啓用警告,請將其打開! – duskwuff
哦!我多麼愚蠢。那爲什麼'x'總是分配0? – darksky
@Nayefc - 如果你缺少一個'return'語句並且你使用了返回值,那麼這個行爲是不確定的。通常你得到的返回值是垃圾,例如。在很多x86環境下,它只會發生在寄存器'eax'中。 – asveikau