Alan said:
hi all,
I want to define a constant length string, say 4
then in a function at some time, I want to set the string to a
constant value, say a
below is my code but it fails
what is the correct code?
many thx!
char string[4] = {0};
string = 'a '; /* <-- failed */
memcpy("abcd", string, sizeof(string));
- Pete
memcpy seems overkill for this, plus the usage is:
memcpy(destination, source, no_of_bytes);
On top of that, the memcpy call above would use up every existing
position in the char array, leaving no terminating NUL, which could
definitely lead to serious nastiness.
To initialize the string, an equivalent but in IMO clearer way to do
it would be:
char string[4] = ""; // still all nulled out
The point is to self-document the intention; you're representing an
empty "string" as opposed to "a bunch of numeric bytes". If you really
want to underscore the fact that the first byte is a "NUL" (the
character variety), you can instead say:
char string[4] = {'\0'}; // but please don't.
To change the value of the string, plain old strcpy works:
strcpy(string, "a");
If you're concerned about possibly overwriting the four available
bytes of the array (it wouldn't happen with the call above, but might
if you don't know for sure what the length of the string you're
copying from is), consider strncpy:
strncpy(string, some_source_ptr, 4);
However, this _still_ has the potential of leaving string without a
terminating null. You just have to be careful.
BTW, the 4's sprinkled throughout the code are bad style. In C, use a
#define to set that length up at the top somewhere...
Good luck,
-leor
Leor Zolman
BD Software
(e-mail address removed)
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at
www.bdsoft.com/tools/stlfilt.html