I'm trying to pass a char*'s memory address as a void* , then to convert the void * memory address back to a string somewhere else. So I have,
char *text // text="somestring";
void *memadrs=&text;
now I'm trying to convert from the void *memadrs to a new char *.
I apologize if there are other topics concerning this already, but with my searches and confusion regarding pointers/referencing them I could not find anything relevant enough to satisfy this.
Cheers for the help!
edit: Sorry for the confusion folks, the char* isn't a constant.
Given const char* text = "somestring", you really should cast to const void* using const void* memadrs = text. This is because "somestring" is a read-only null-terminated string literal. Note that you don't need to use the address-of operator & since text is already a pointer type.
Using a const void* cast helps the emission of compile-time errors if a subsequent cast to char* is attempted. This is useful since the behaviour behaviour on casting memadrs to a char* and then modifying the memory would be undefined since the original memory is read-only.
A C standard reference to back this up:
[C99: 6.7.3/5]: If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
To cast back to a const char*, use (const char*)memadrs.
My switching of char const* to const char* is simply personal taste.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With