我正在学习C语言中的二进制搜索,并且已经运行了这个简单的程序,它将为我返回要在该数组中找到的任何数字的数组索引。但是这段代码给了我“ collect2:错误:ld返回了1个退出状态”。我将Clion与Cygwin编译器结合使用。
有人可以告诉我在哪里需要修复代码才能使代码正常工作?而且,将来我该避免该特殊错误怎么办? TIA。
代码如下:
#include <stdio.h>
int searchNumber(int arr[], int n, int x);
// printf("");
int main() {
int i, n, store;
printf("Length of array: ");
scanf("%d", &n);
int arr[n];
//Taking the values of the array
for(i =0; i<n; i++)
{
printf("Enter the value of arr[%d]: ", i);
scanf("%d", &arr[i]);
}
//Printing the values
for(i =0; i<n; i++)
{
printf("Value of arr[%d]: %d\n", i, arr[i]);
}
store = searchNumber(arr, n, 5);
printf("%d", store);
//custom function
int searchNumber(int arr[], int n, int x){
int left, right, mid;
left =0;
right = n-1;
while(left <= right)
{
mid = (left + right) / 2;
if(arr[mid] == x)
{
return mid;
}
if(x > arr[mid])
left = mid + 1;
else{
right = mid - 1;
}
}
return -1;
}
return 0;
}
这是完整的错误消息:
/usr/lib/gcc/x86_64-pc-cygwin/9.3.0/../../../../x86_64-pc-cygwin/bin/ld: CMakeFiles/Binary.dir/BInnarry.c.o: in function `main':
/cygdrive/c/Users/slevin/CLionProjects/mama/BInnarry.c:26: undefined reference to `searchNumber'
/cygdrive/c/Users/slevin/CLionProjects/mama/BInnarry.c:26:(.text+0x12a): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `searchNumber'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/Binary.dir/build.make:84: Binary.exe] Error 1
make[3]: Leaving directory '/cygdrive/c/Users/slevin/CLionProjects/mama/cmake-build-debug'
make[2]: *** [CMakeFiles/Makefile2:134: CMakeFiles/Binary.dir/all] Error 2
make[2]: Leaving directory '/cygdrive/c/Users/slevin/CLionProjects/mama/cmake-build-debug'
make[1]: *** [CMakeFiles/Makefile2:141: CMakeFiles/Binary.dir/rule] Error 2
make[1]: Leaving directory '/cygdrive/c/Users/slevin/CLionProjects/mama/cmake-build-debug'
make: *** [Makefile:144: Binary] Error 2
答案 0 :(得分:1)
尝试从main()函数中移出searchNumber()函数定义:
#include <stdio.h>
int searchNumber(int arr[], int n, int x);
// printf("");
int main() {
int i, n, store;
printf("Length of array: ");
scanf("%d", & n);
int arr[n];
//Taking the values of the array
for (i = 0; i < n; i++) {
printf("Enter the value of arr[%d]: ", i);
scanf("%d", & arr[i]);
}
//Printing the values
for (i = 0; i < n; i++) {
printf("Value of arr[%d]: %d\n", i, arr[i]);
}
store = searchNumber(arr, n, 5);
printf("%d", store);
return 0;
}
//custom function
int searchNumber(int arr[], int n, int x) {
int left, right, mid;
left = 0;
right = n - 1;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] == x) {
return mid;
}
if (x > arr[mid])
left = mid + 1;
else {
right = mid - 1;
}
}
return -1;
}