I want to copy two parts of string s to two strings a and b:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "0123456789ABCDEF";
char a[10];
char b[6];
strncpy( a, s, 10 );
a[10] = '\0';
printf("%s\n", a);
strncpy( b, s+10, 6 );
b[6] = '\0';
printf("%s %s\n", a, b);
return 0;
}
Result:
0123456789
ABCDEF
I had expected
0123456789
0123456789 ABCDEF
What has happened to a? Can anybody tell me what is wrong?
The arrays a and b do not contain strings. Declare them like
char a[11];
char b[7];
that is reserve one more element for the terminating zero character.
Otherwise these statements
a[10] = '\0';
b[6] = '\0';
use invalid indices.