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
is not const
). I tried stringB=(char*) stringA
, but that makes stringB
still point to the same memory location, so when stringA
later changes, stringB
does too.
I've also tried strcpy(stringB,stringA)
, but it seems that if stringB
wasn't initialized to a large enough array, there's a segfault. I'm not super experienced with C strings though, am I missing something obvious?
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? If stringB
is checked for equality with other C-strings, will the extra space affect anything?
(And just using strings isn't a solution here, as I need minimal overhead and easy access to individual characters.)
See Question&Answers more detail:os