Что означает ошибка "недопустимые типы ... для индекса"? - PullRequest
0 голосов
/ 22 сентября 2019

Я вижу несколько ссылок на эту ошибку в 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]’, а я все еще не знаю, кто такой.

Может кто-нибудь помочь мне понять эту ошибку?

1 Ответ

1 голос
/ 22 сентября 2019
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...
...