Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof() of this array illegal?

Tags:

c++

arrays

sizeof

I have the following array:

static std::pair<const Type, const size_t> typemap_[];

defined as

std::pair<const talos::Message::Type, const size_t> talos::Message::typemap_[8] = {
{ talos::Message::Type::Empty, typeid(int).hash_code() },
{ talos::Message::Type::Keyboard , typeid(int).hash_code() },
...

Why does this

sizeof(typemap_);

give a compile time error

Error C2070 'std::pair []': illegal sizeof operand

even though this

sizeof(typemap_[0]);

is legal and the array is of a fixed size?

Type is a defined as:

enum class Type {...} 
like image 477
Mathis Avatar asked Mar 06 '23 12:03

Mathis


1 Answers

Seems the compiler is missing the definition of the typemap_ variable. Since it's static you probably have it hidden in one of the source files.

If you put everything you have now into the same source the solution will work. For example:

enum class Type {None, Some} ;
static std::pair<const Type, const size_t> typemap_[] = {
    { Type::None, typeid(int).hash_code() },
    { Type::Some , typeid(int).hash_code() },
};

int main() {
    std::cout << "sizeof: " << sizeof(typemap_) << " " << sizeof(typemap_[0]);
    return 0;
}

Works well and outputs sizeof: 32 16.

Same time sizeof of a single element is legal since the compiler knows what the array consists of even without knowing its actual size.

like image 109
Dusteh Avatar answered Mar 17 '23 01:03

Dusteh