Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type cast from unsigned const char * to char const *

Tags:

c++

c

visual-c++

I want to convert unsigned const char * to char const * for passing into strcpy function

Please suggest some method

like image 528
Sijith Avatar asked Jan 14 '23 04:01

Sijith


2 Answers

(const char *) my_signed_char

In C++ there are more idiomatic ways to cast this, but since you are using strcpy you are not programming idiomatic C++ it seems.

like image 82
wirrbel Avatar answered Jan 21 '23 12:01

wirrbel


This works for me; is it what you had in mind?

#include <stdio.h>
#include <string.h>

int main(int argc, char ** argv)
{
   const char foo[] = "foo";
   unsigned const char * x = (unsigned const char *) foo;

   char bar[20];
   strcpy(bar, (const char *)x);

   printf("bar=[%s]\n", bar);
   return 0;
}

Note that if you are instead trying to pass the (unsigned const char *) pointer into strcpy's first argument, then you are probably trying to do something you shouldn't (and the compiler is right to flag it as an error); because strcpy() will write into the memory pointed to by its first argument, and a const pointer is a pointer whose data should not be written to.

like image 28
Jeremy Friesner Avatar answered Jan 21 '23 10:01

Jeremy Friesner