This seems like it should be really simple, but for some reason, I’m not getting it to work. I have a string called seq, which looks like this:
ala
ile
val
I want to take the first 3 characters and copy them into a different string. I use the command:
memcpy(fileName, seq, 3 * sizeof(char));
That should make fileName = "ala", right? But for some reason, I get fileName = "ala9". I’m currently working around it by just saying fileName[4] = '\0', but was wondering why I’m getting that 9.
Note:
After changing seq to
ala
ile
val
ser
and rerunning the same code, fileName becomes "alaK". Not 9 anymore, but still an erroneous character.
C uses a null terminator to denote the end of a string. memcpy doesn’t know that you’re copying strings (it just copies bytes) so it doesn’t think to put one on. The workaround you have is actually the right answer.
Edit: wolfPack88 has a good point. You really need to be changing filename[3]. Also, the below comments bring up some great points about strncpy which is a choice worth learning too.