我可以在SO上看到对此错误的多次引用,尽管答案似乎都解决了原始编译错误,但没有一个解释错误的真正含义。
我正在编译我的 cpp 文件:g++ -Wall -std=c++11 myfile.cpp
,并得到以下错误:
myfile.cpp: In function ‘void GenerateMatrix(uint8_t**, uint8_t)’:
myfile.cpp:32:39: error: invalid types ‘uint8_t {aka unsigned char}[uint8_t {aka unsigned char}]’ for array subscript
std::cout << ", " << (*matrix)[i][j];
我的代码:
#include <iostream>
//// populates an n x n matrix.
//// @return the matrix
void GenerateMatrix(uint8_t** matrix, uint8_t n)
{
*matrix = (uint8_t*)malloc(n * n);
uint8_t* pc = *matrix;
for(uint8_t i = 0; i < n; i++)
{
for(uint8_t j = 0; j < n; j++)
{
*pc++ = i+j;
}
}
for(uint8_t i = 0; i < n; i++)
{
for(uint8_t j = 0; j < n; j++)
{
std::cout << ", " << (*matrix)[i][j];
}
std::cout << "n";
}
}
int main()
{
uint8_t* matrix = nullptr;
uint8_t n = 10;
GenerateMatrix(&matrix, n);
return 0;
}
我尝试更改i
并在第二个循环中j
以int
.这给了我一个类似的错误,但这次的抱怨是关于invalid types ‘uint8_t {aka unsigned char}[int]’
,我仍然不明智。
谁能帮我理解这个错误?
void generateMatrix(uint8_t** matrix, uint8_t n)
// ^^
{
(*matrix) // type is uint8_t*
[i] // type is uint8_t
[j]; // ???
}
你实际做的相当于:
uint8_t n = 10;
n[12] = 7; // no index ('subscript'!) applicable to raw unsigned char
// or with compiler words, the unsigned char is an invalid
// type for this operation to be applied on...
在另一个方向上也可能出现相同的消息:
class C { }; // note that there's no cast operator to some integral type provided!
int array[7];
C c;
array[c]; // just that this time it's the other operand that has invalid type...