You must use filename[3]='\0'; . Why this is necessary: because nothing else set the NUL terminator for the string, so you need to.
Edit: Of course, for real use, you are not using a constant, as shown above. Usually you use something like:
char *substring(char *out, char const *in, size_t len) { memcpy(out, in, len); out[len] = '\0'; return out; }
Note that you really had the right idea using memcpy . strncpy (for an obvious example) is not quite what you need to use for this (or almost any other) purpose. In the list of standard library functions that should be avoided, strncpy takes the second place in the list, only gets behind (although, in fairness, I must indicate that strtok is a close third).
Also note that (like most standard library functions) this does not attempt to check the parameters that you pass, for example, if you tell him to copy 99 characters from a string up to 10 characters long to the buffer, long characters, he will try to copy 99 characters anyway by creating undefined behavior).
Edit2: One option is to use sprintf .
Jerry Coffin
source share