void split(char array[]) {
int length, length2, half;
char first_half[BUF], sec_half[BUF];
length = strlen(array);
length2 = length / 2;
length -= length2;
strncpy(first_half, array, length - 1);
strncpy(sec_half, (array + length), length2 - 1);
printf("%s\n", first_half);
printf("%s\n", sec_half);
}
If input is "People", it outputs: Pe0z plcy etc... Just wondering what's the problem here.
My question is not the same as the question mentioned. I am not trying to insert a word in the middle of another word, I am trying to split a word in half and put the two halves in two strings.
It is enough if you initialize the buffers with 0 as shown in
split1(...)Then termination will be automatic.
The uninitialized buffer contains random characters. If buffers are not zeroed the termination is needed as shown in
split2(...)The solutions are as close as possible to the original code. They work for even, odd and empty strings.
Please note the symmetry of the solutions with
memcpyandstrncpy.Output: