I’m learning about strings in c. I am using code::blocks as a compiler, even though it’s not just for c. So, the problem with the code below is that the output for string2 is the stored 5 characters plus string1’s output. I’ll show you:
#include <stdio.h>
#include <string.h> /* make strncpy() available */
int main()
{
char string1[]= "To be or not to be?";
char string2[6];
/* copy first 5 characters in string1 to string2 */
strncpy (string2, string1, 5);
printf("1st string: %s\n", string1);
printf("2nd string: %s\n", string2);
return 0;
}
Output is:
1st string contains: To be or not to be?
2nd string contains: To be To be or not to be?
If you ask me, that’s a lot more than 5 characters…
You are not terminating string2 with ‘\0’, so the printf overruns. Try to do:
before using string2.
or, since you know you are copying 5 chars, after strncpy:
so you properly terminate correctly the string.
pay attention to the fact that you should put ‘\0’ after exactly the number of characters you did copy, otherwise you will see garbage even in the middle of the string.