>>>> So what is the correct way to do this?
The c_str returns a const char* to trhe internal buffer of the string. As it was const you get an compilation error when assigning it to a non-const.
>>>> strcpy(myTest.name, aString.c_str()); //Stack Core dump during runtime.
crashes because myTest.name is a pointer pointing to nowhere probably NULL. You need to allocate memory before copying.
>>>> So what is the correct way to do this?
Either use a string member in the struct (recommended).
Or use a fixed char array:
struct TEST
{
char name[64]; // don't be stingy
};
...
int len = min(sizeof(myTest.name)-1,
strncpy(myTest.name, aString.c_str(), len);
myTest.name[len] = 0; // set terminating zero
I use the strncpy here (and not strcpy) as it would consider the size of the fixed array.
You see it isn't quite easy to make safe copies with char arrays.
Or use dynamic allocation:
myTest.name = new char[aString.size()+1];
strcpy(myTest.name, aString.c_str());
That would work with your current struct BUT you have to care for freeing after use and before each update which might need more space than the current allocation.
Main Topics
Browse All Topics





by: Let_Me_BePosted on 2009-09-01 at 08:42:56ID: 25232744
1) fails because c_str() returns const char*. You cant assign const char* to char* (you would be discarding the constant). Also, c_str() is not guaranteed to return something that will be persistent, after next operation on top of aString, it may become an invalid pointer.
; strcpy(myTest.name,aString .c_str()); Don't forget to free the memory after you don't need it.
2) fails because char* is just a pointer, a variable that can store an address. So you need to allocate memory before you can copy a string. myTest.name = malloc(aString.length()+1)