Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Converting a char to a const char *

Tags:

c++

char

pointers

I'm trying to use beginthreadex to create a thread that will run a function that takes a char as an argument. I'm bad at C++, though, and I can't figure out how to turn a char into a const char , which beginthreadex needs for its argument. Is there a way to do that? I find a lot of questions for converting a char to a const char, but not to a const char *.

like image 684
user3098417 Avatar asked Dec 13 '13 07:12

user3098417


People also ask

Can a char * be passed as a const * argument?

Yes, it's acceptable.

How do I cast a character to const char?

a simple c-style cast will do. const char * destPtr = (const char *)srcPtr; infact you dont need any casting. converting char to const char doesnt require any cast. had it been opposite then you need a simple cast..

Can a char be passed as a const char?

Yes it is allowed.

Can const char * Be Changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.


2 Answers

char a = 'z';
const char *b = &a;

Of course, this is on the stack. If you need it on the heap,

char a = 'z';
const char *b = new char(a);
like image 159
Paul Draper Avatar answered Sep 22 '22 10:09

Paul Draper


If the function expects a const pointer to an exiting character you should go with the answer of Paul Draper. But keep in mind that this is not a pointer to a null terminated string, what the function might expect. If you need a pointer to null terminated string you can use std::string::c_str

f(const char* s);

char a = 'z'; 
std::string str{a};
f(str.c_str());
like image 27
hansmaad Avatar answered Sep 19 '22 10:09

hansmaad