I am writing a function in C which takes two strings of the same length,
for example:-
S1 = "Hello" and S2 = "12345"
and returns a result that mixes the characters from the input strings so that the first char in the result string is the first char from S1, the second char is the first char from S2, the third char in r is the second char from S1 and the fourth char in r is the second char from S2, and so on....
So if:-
S1 = "Hello"
S2 = "12345"
Result = "H1e2l3l4o5"
My function looks like this:
#include <stdio.h>
#include <string.h>
char* mix(char *s1, char *s2)
{
int length = strlen(s1);
char* result = malloc(sizeof(char) * length * 2);
int i, j;
for(i = 0, j = 0; i < (length); i++, j = j + 2)
{
result[j] = s1[i];
result[j + 1] = s2[i];
}
return result;
}
For the values of S1 and S2 above it produces:
`H1e2l3l4o5:=C:\Uºt6▄╘º`
Which confuses me as I didn't allocate "result" enough memory for that many chars and wasn't warned of a segmentation fault or anything of that nature. Have I obviously done something wrong?