为什么错误一直在 C 中为数组声明不兼容的整数到指针?

Why does the error keep stating incompatible integer to pointer in C for an array?

我在进行二分查找,不知道是我的递归语句有问题还是我没有正确使用数组,但我无法找出问题所在。 错误一直提示我在递归语句中的nValues前面加一个'&'符号,我也不明白。

#include <cs50.h>

#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */

bool search(int value, int values[], int n)
{
    if (n < 0) //return 0 if negative
        return 0;
    else
    {
        if(values[(int)(n/2)] == value) //if value is found return true
            return 1;
        else if(value < values[(int)(n/2)]) //if value is less than middle, search bottom half
        {
            int nValues[(int)(n/2)-1]; //make an array of size bottom half
            for(int i = 0; i < (int)n/2; i++) //put in bottom half into a new array
            {
                nValues[i] = values[i];
            }
            search(value, nValues[(int)(n/2)-1], (int)(n/2)-1); //recursion with bottom half of the array
        }
        else if(value >values[(int)(n/2)]) //if higher than middle, search upper half
        {
            int nValues[(int)(n/2)+1]; //make an array of size upper half
            for(int i = (int)(n/2); i< n; i++) //iterate through the top half to create new array 
            {
                nValues[i] = values[i]; 
            }
            search(value, nValues[(int)(n/2)+1], (int)(n/2)); //recursion with upper half of the array
        }

    }
    return 0; //if all fails, return false

}

根据你问题的措辞,我猜你对指针的概念不熟悉。在 C 中,指针是一种存储另一个变量的内存地址的类型。 & 运算符检索变量的内存地址。

int i = 4;    // < An integer variable equal to 4
int* ip = &i; // < A pointer variable equal to the memory address of i

在 C 中,数组被处理为指向数组第一个(第 0 个)元素的指针。

int a[] = {0, 1, 2, 3};
a == &a[0] // The name of the array is the same as the address of the first element

您所遇到的困惑是由 [] 运算符的双重使用引起的。当用作声明时,[] 表示指针(因为数组与指针相同)。在表达式中使用时,[] 访问数组的元素。

您的方法声明要求参数 int values[],因为它是声明,所以意味着指向 int 的指针。在您的递归调用中,您提供了参数 nValues[(int)(n/2)+1],因为它是一个表达式,它访问数组的第 (n/2)+1 个元素,它是一个 int,而不是指向 int.

附带说明,n 是一个整数,2 是一个整数,所以 n/2 也是一个整数。没有理由投它。