一元'*'的类型参数无效(有"布尔")

invalid type argument of unary '*' (have 'bool')

本文关键字:布尔 类型参数 一元 无效      更新时间:2023-10-16

我对C++很陌生,目前正在尝试学习指针。下面是我的程序的代码,我收到错误:

错误:一元"*"的类型参数无效(具有"布尔")

我正在尝试为数组指针的i index设置一个新值。我在这里做错了什么?

int opendoors(int n, int r)
{
    bool * open = new bool[n];
    for (int i = 0; i <= n; i++)
    {
        *open[i] = 1;
    }
    int incdoor = 1;
    for (int i = 0; i < r; i++)
    {
        for (int j = n - 1; j >= 0; j--)
        {
            *open[i - incdoor] = 0;
        }
        for (int k = 0; k < n; k++)
        {
            *open[i + incdoor] = 1;
        }
        incdoor++;
    }
    int count = 0;
    for (int i = 0; i <= n; i++)
    {
        if (*open[i] == 1)
        {
            count++;
        }
    }
    delete [] open;
    return count;
}
int main()
{
    int n, r;
    std::cin >> n >> r;
    std::cout << opendoors(n, r) << std::endl;
    return 0;
}

只做open[i] .可以在指针上使用数组索引或取消引用运算符,但不能同时使用两者。

这不是对问题的直接回答,但您应该注意这一点。您的代码中存在错误。您的函数接受两个整数参数和第一个参数n用于创建布尔变量的动态数组。然而;在设置循环范围以在动态数组上工作的两个 for 循环中,您使用了错误的比较运算符 <= 。这应该是<.你能猜出为什么吗?当您开始在数组中使用索引时,它们0基于数组。因此,假设您将3传递到函数的第一个参数中;然后,这将创建 3 个布尔变量的动态数组。现在在你的 for 循环中,你的索引i0 开始,这是正确的,但是当它与<=进行比较时,让我们看看会发生什么:

i = 0; // First Index
i = 1; // Second Index
i = 2; // Third Index
i = 3; // Fourth Index - Still a Valid pass of the for loop because the condition is true;
       // however, we have a memory problem because the index i is out of bounds as there 
       // are only 3 bools in the array and not 4.