错误 "invalid types ... for array subscript" 是什么意思?

What does the error "invalid types ... for array subscript" mean?

我可以在 SO 上看到对这个错误的几个引用,虽然所有答案似乎都解决了原始编译错误,但其中 none 解释了错误的真正含义。

我正在编译我的 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;
}

我尝试将第二个 for 循环中的 ij 更改为 int。那给了我一个类似的错误,但这次投诉是关于invalid types ‘uint8_t {aka unsigned char}[int]’,我还是none更聪明。

谁能帮我理解这个错误?

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...