assigning a C string to a string object

Hi -

I just want to double-check something with the forum. If I have something like:

1
2
3
4
5
string myStr;
char cStr[80];

strcpy(cStr, "abcde");
myStr = cStr;


Should I expect that subsequent calls to myStr.length() should return the correct length? I ask because I'm using a compiler that doesn't seem to be doing this for me.

Thanks.

mz
Should I expect that subsequent calls to myStr.length() should return the correct length?

Yes. The correct length is 5, just to make sure we're on the same page.

I ask because I'm using a compiler that doesn't seem to be doing this for me.

You probably have undefined behavior elsewhere.
just checked internal values in my debugger and all is working correctly.

Arthar is correct.
Thanks, Athar...but what do you mean by "undefined behavior?"

And, am I correct in assuming that if there were a "\r\n" appended to the "abcde" in the C string, then after the assignment, myStr.length() would be 7?
Undefined behavior includes writing beyond array bounds or trying to access destroyed objects.
http://en.wikipedia.org/wiki/Undefined_behavior

then after the assignment, myStr.length() would be 7?

Yes... after the assignment.
Last edited on
Thanks for the clarification. Turns out that this was cockpit error; in the same routine, I assigned myStr.c_str() to a character pointer, then manipulated the pointer. Guess that's not kosher. Now fixed.
Topic archived. No new replies allowed.