我在SO上可以看到多次对此错误的引用,尽管所有答案似乎都可以解决原始的编译错误,但没有一个可以解释错误的真正含义。
我正在使用g++ -Wall -std=c++11 myfile.cpp
编译我的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;
}
我尝试在第二个for循环中将i
和j
更改为int
。这给了我一个类似的错误,但是这次投诉是关于invalid types ‘uint8_t {aka unsigned char}[int]’
的,但我仍然不明智。
有人可以帮助我理解此错误吗?
答案 0 :(得分:1)
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...