Is there an easy way to copy C strings?
I have const char *stringA, and I want char *stringB to take the value (note that stringB
If I just initialize stringB as char *stringB[23], because I know I'll never have a string longer than 22 characters (and allowing for the null terminator), is that the right way?
Almost. In C, if you know for sure that the string will never be too long:
char stringB[MAX+1];
assert(strlen(stringA) <= MAX));
strcpy(stringB, stringA);
or, if there's a possibility that the string might be too long:
char stringB[MAX+1];
strncpy(stringB, stringA, MAX+1);
if (stringB[MAX] != '\0') {
// ERROR: stringA was too long.
stringB[MAX] = '\0'; // if you want to use the truncated string
}
In C++, you should use std::string, unless you've proved that the overhead is prohibitive. Many implementations have a "short string optimisation", which will avoid dynamic allocation for short strings; in that case, there will be little or no overhead over using a C-style array. Access to individual characters is just as convenient as with a C-style array; in both cases, s[i] gives the character at position i as an lvalue. Copying becomes stringB = stringA; with no danger of undefined behaviour.
If you really do find that std::string is unusable, consider std::array: a copyable class containing a fixed-size array.
If stringB is checked for equality with other C-strings, will the extra space affect anything?
If you use strcmp, then it will stop at the end of the shortest string, and will not be affected by the extra space.