我对C++
很陌生,目前正在尝试学习指针。以下是我的程序的代码,我收到错误:
错误:一元' *'的无效类型参数(有' bool')
我试图为数组指针的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;
}
答案 0 :(得分:3)
做open[i]
。您可以在指针上使用数组索引或取消引用运算符,但不能同时使用两者。
答案 1 :(得分:0)
这不是您问题的直接答案,但您应该注意这一点。您的代码中存在错误。您的函数需要两个整数参数,并且您使用第一个参数n
来创建布尔变量的动态数组。然而;在两个for循环中,您要设置循环范围,以便在动态数组上使用错误的比较运算符<=
。这应该是<
。你能猜到为什么吗?当您开始将索引用于数组时,它们基于0
。所以,假设您将3
传递给函数的第一个参数;然后,这将创建3个布尔变量的动态数组。现在,在for循环中,您可以在i
处开始索引0
,这是正确的,但当与<=
进行比较时,让我们看看会发生什么:
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.