Weird value when I declare a string in C
I want to declare a string that will hold 4 chars 开发者_运维技巧
char st[4];
memcpy(st,"test",4);
but when I print st ... I have "test" and some other symbols printed after it - what is wrong in that ?
Thanks a lot
C strings, like the "test"
string literal, are NUL-terminated, meaning the last character is '\0':
{'t', 'e', 's', 't', '\0'}
You would need to use st[5]
, and copy 5 characters, to have room for (and include) the NUL. As is, you're not including it in the copy. So aftewards, st
looks like:
{'t', 'e', 's', 't', X, X, X ... '\0'}
When you print, C keeps reading gibberish values that are coincidentally in memory (X'es above) until it finds a NUL.
The best solution is to eliminate memcpy
, and let the compiler figure out the size from your initialization:
char st[] = "test";
sizeof(st)
will now be 5.
If you really want to use memcpy()
, you have to copy the terminating null-byte as well:
char st[5];
memcpy(st, "test", 5);
remember, in memory "test"
looks like that:
74 65 73 74 00
t e s t \0
that's why you have to copy 5 bytes.
If you don't copy the null byte, functions that work on null terminated strings, such as printf()
, will read the memory until they reach some random null-byte...
If for some weird reason want to keep your code as is, do the following:
char st[4];
memcpy(st,"test",4);
int i;
for(i = 0; i < 4; i++)
printf("%c",st[i]);
Now it will print ok. But read the other answers to see that your programming is not ok.
精彩评论