Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid conversion from ‘const char*’ to ‘unsigned char*’

A simple C++ code:

int main(){
unsigned char* t="123";
}

on compilation with g++ gives following error:

invalid conversion from ‘const char*’ to ‘unsigned char*’ [-fpermissive]

Why?

like image 330
anupamD Avatar asked Dec 26 '15 11:12

anupamD


2 Answers

In C++ string literals have types of constant character arrays. For example string literal "123" has type const char[4].

In expressions with rare exceptions arrays are converted to pointers to their first elements.

So in this declaration

unsigned char* t="123";

the initializer has type const char *. There is no implicit conversion from const char * to unsigned char *

You could write

const unsigned char* t = reinterpret_cast<const unsigned char *>( "123" );
like image 200
Vlad from Moscow Avatar answered Oct 23 '22 19:10

Vlad from Moscow


Another approach, which gets you a modifiable unsigned char array as you originally wanted, is:

#include <cstdlib>
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    unsigned char ta[] = "123";
    unsigned char* t = ta;

    cout << t << endl;  // Or ta.

    return EXIT_SUCCESS;
}

You can add const to both declarations if you wish, to get const unsigned char without an explicit cast.

like image 43
Davislor Avatar answered Oct 23 '22 17:10

Davislor