一元'*'的类型参数无效(有"布尔")
invalid type argument of unary '*' (have 'bool')
我对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 循环中,你的索引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.
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 了解布尔运算符==(参数 1,参数 2)
- 具有可变参数非类型参数的模板专用化
- 类中的虚拟布尔函数参数不起作用
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 布尔类型的参数不匹配
- 一元'*'的类型参数无效(有"布尔")