This line:
a[strlen(a) + i + 1] = b[i];
writes characters one position further than you want.
When called in your example, your routine is passed a
and b
with these contents:
a[0] = 'e'
a[1] = 'g'
a[2] = 'g'
a[3] = 0
b[0] = 's'
b[1] = 'a'
b[2] = 'm'
b[3] = 'p'
b[4] = 'l'
b[5] = 'e'
b[6] = 0
You want to produce this result:
a[0] = 'e'
a[1] = 'g'
a[2] = 'g'
a[3] = 's'
a[4] = 'a'
a[5] = 'm'
a[6] = 'p'
a[7] = 'l'
a[8] = 'e'
a[9] = 0
However, since your code writes to a[strlen(a) + i + 1]
, it writes the first character to a[strlen(a) + 0 + 1]
, which is a[4]
. You want it in a[3]
. You could change strlen(a) + i + 1
to strlen(a) + i
, but then, when you have written the first character, you will have overwritten the null terminating character, and strlen
will not work to find the length anymore. To fix this, you can remember the length of a
before entering the loop. Consider this code:
int i = 0;
int LengthOfA = strlen(a);
for (i = 0; i < strlen(b); ++i)
{
a[LengthOfA + i] = b[i];
}
That will write the characters to the correct place.
However, it does not put a null terminating character at the end of a
. To do that, we can put another statement after the loop:
a[LengthOfA + i] = 0;
At that point, your routine will work for normal situations. However, there are two more improvements we can make.
First, instead of using int
for lengths and indices, we can use size_t
. In C, the width of int
is flexible, and size_t
is provided as a good type to use when dealing with sizes of objects. To use it, first use #include <stddef.h>
to get its definition. Then your code can be:
size_t i = 0;
size_t LengthOfA = strlen(a);
for (i = 0; i < strlen(b); ++i)
{
a[LengthOfA + i] = b[i];
}
a[LengthOfA + i] = 0;
Second, your code nominally calculates strlen(b)
in every iteration. This is wasteful. It is preferable to calculate the length once and remember it:
size_t i = 0;
size_t LengthOfA = strlen(a);
size_t LengthOfB = strlen(b);
for (i = 0; i < LengthOfB; ++i)
{
a[LengthOfA + i] = b[i];
}
a[LengthOfA + i] = 0;