cannot convert from 'std::string' to 'void *'
alex Ioan

error C2440: '=' : cannot convert from 'std::string' to 'void *'


string name;
peer -> data = name;

So... how to make this work ?
I basically have to convert string to void and void to string afterwards...
tried "peer -> data = &name;" but that adds letters and numbers before the actual string...

and the definition of peer: (part of it)

typedef struct _ENetPeer
{ ...
void * data;

and I CANT modify the definition of peer.

Any help is appreciated !

Thomas Fjellstrom

You could try looking up the c_str member of std::string.


The compiler throws this error because you are trying to compare an object with a pointer. If you really want to, you can change the string like this:
std::string* name;
But I don't get why you would want to change it to a void pointer.

I was using the wrong words(compare instead of assign) and I didn't fully read his post. nvm


Sorry, but you are totally wrong. He's not comparing anything, and changing name to be a string pointer won't help much.

The reason for a void pointer is because he's using a library that lets you store your own objects, and the only practical way of allowing this in C/C++ is via void pointers.

Dustin Dettmer
peer->data = malloc(name.size() + 1);
strcpy(peer->data, name.c_str());


cout << "Peer: " << (char*)peer->data << endl;

alex Ioan

@ Dustin Dettmer

That does not work...
it gives me :

'strcpy' : cannot convert parameter 1 from 'void *' to 'char *'

alex Ioan


Tried static cast but did not work...


It should work:

peer->data = (void*)name.c_str();
cout << "Peer->data: " << (char*)peer->data << endl;

alex Ioan

that worked... thanks !
I was trying
peer->data = reinterpret_cast<void*>(&name);
peer->data = reinterpret_cast<void*>(name);
and was not giving me anything


Well that's strange, because that should work just fine as well (first version with the &name).

What do you mean by "was not giving me anything"? If you mean trying to display the data field as a C-string afterwards revealed nothing then I understand.

Consider the following example:

void *data = NULL;
string name("Dennis");
data = reinterpret_cast<void*>(&name);

This compiles and runs just fine. But outputting data as a C string won't work, because all it holds is the address of the name string, which is a C++ datatype and not just a pointer to a zero terminated string, so it contains other data before the actual character data. I've checked in my environment during debug and the first memory byte at the address of name was 0 (which in case of interpreting the data at that address as a zero terminated C "string" (not to confuse with the string type from C++) explains why trying to display that reveals nothing).

Dustin Dettmer
peer->data = malloc(name.size() + 1);
strcpy((char*)peer->data, name.c_str());


cout << "Peer: " << (char*)peer->data << endl;

Thread #606552. Printed from