Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to const void* in c++?

Tags:

c++

string

I have a method, one of whose parameters require a const void* as input.

When i do this, it works -

const void *a = "abc"; \\abc is also a string though.

I've tried assigning a string variable to a const void* variable, but it gave some errors. Why can't i directly assign a string variable to a const void* variable?

How can i convert a string to a const void* ?

Is there any other way around ?

Thanks,

like image 419
Ashish Avatar asked Jan 09 '23 22:01

Ashish


1 Answers

If by "string", you mean std::string, then that's a class type, which isn't directly convertible to a pointer. A string literal like "abc" is a character array, which is convertible to a pointer.

If you want a pointer to the string's character array, then you can access that via the c_str function:

const void * a = my_string.c_str();

Beware that the pointer can become invalid if you destroy or modify the string.

like image 121
Mike Seymour Avatar answered Jan 19 '23 22:01

Mike Seymour