Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot initialize a member subobject of type 'const signed char *' with an lvalue of type 'const char [X]'

Tags:

c++

I have the following code :

typedef       signed char         Char;

static const struct MyStruct
{
    const Char* str;
    // Other fields
}
myList[] =
{
    {"none", /* Other fields */},
    {"main", /* Other fields */},
}

But I have compilation errors :

Cannot initialize a member subobject of type 'const Char *' (aka 'const signed char *') with an lvalue of type 'const char [X]

X is string length

It's OK when I replace Char by char, but how can I use signed char ?

like image 493
A.Pissicat Avatar asked Jan 30 '23 10:01

A.Pissicat


2 Answers

"none", for example is a const char[5] type. Under certain circumstances, this can decay to a const char*.

Irrespective as to whether char is signed or unsigned on your platform, char, signed char, and unsigned char are always distinct types.

C++ does not allow direct decay of a const char[N] type to anything other than a const char* (or a pointer to a typedef of const char*), so in your case it is required to issue a diagnostic.

In C++ you have so many other alternatives: std::string being the obvious choice in your case.

To examine the type of char you have, use

std::numeric_limits<char>::is_signed

from <limits>.

like image 157
Bathsheba Avatar answered Feb 08 '23 17:02

Bathsheba


but how can I use signed char ?

By using an array of signed char instead of a string literal:

signed char none[] = {'n','o','n','e','\0'};

...

myList[] =
{
    {none, /* Other fields */},
    ...
}

Note that char (the type of the character literal) may be unsigned and if the value is not representable by signed char, then the resulting value will be implementation defined.

like image 25
eerorika Avatar answered Feb 08 '23 17:02

eerorika