Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How correctly copy CString to char * variable. 1

Status
Not open for further replies.

sulacco

Technical User
Nov 8, 2002
74
RU
Hi, People. How correctly copy CString to char * variable.
I have:
Code:
 char * message;
 CString strContent;

 //this one is throwing an exception 
 memcpy(message,str.GetBuffer(str.GetLenght(),str.GetLength());
How do you do it, pros?
 
First of all, if you're doing exactly what you put in that example, then it's definitely going to blow up.
You need to either allocate memory to the char* or make it an array of char. Otherwise you are copying memory into who knows where in memory!
Second, you should use strcpy().
Example:
Code:
#include <cstring>  // For strcpy().
#include <afx.h>

int main( void )
{
    char szMessage[ 80 ];
    CString strContent = "Hello World";

    strcpy( szMessage, strContent.GetBuffer(80) );
}
 
char* message;
CString strContent;

//...

message = (char*)(LPCTSTR)strContent;

// That's it!
 
Well, thanks. But I've got impression that the last example
is just copying pointer from strContent to message.
Code:
message = (char*)(LPCTSTR)strContent;
and now message points to strContent buffer?

 
strContent is type-cast to a FAR t_char pointer, then to a char pointer. The reason it works is because during cast, the only part of the CString structure that aligns with a char[] is the string buffer itself. Otherwise, you wouldn't be able to do this since the compiler would complain that there is no part of the structure that can be properly converted. Either way, try it and see for yourself. Set a breakpoint after the cast and check the contents of message.
 
That would be dangerous wouldn't it? If the contents of the CString changes, the char* pointer could suddenly be pointing to something other than the CString buffer.
Also, the question was how to copy the CString to char*, not just to copy the pointer.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top