Weird value when I declare a string in C -
i want declare string hold 4 chars
char st[4]; memcpy(st,"test",4);
but when print st ... have "test" , other symbols printed after - wrong in ?
thanks lot
c strings, "test"
string literal, nul-terminated, meaning last character '\0':
{'t', 'e', 's', 't', '\0'}
you need use st[5]
, , copy 5 characters, have room (and include) nul. is, you're not including in copy. aftewards, st
looks like:
{'t', 'e', 's', 't', x, x, x ... '\0'}
when print, c keeps reading gibberish values coincidentally in memory (x'es above) until finds nul.
the best solution eliminate memcpy
, , let compiler figure out size initialization:
char st[] = "test";
sizeof(st)
5.
Comments
Post a Comment