I am having trouble concatenating strings in C, without strcat library function. Here is my code
#include
#include
#include<
Problems:
length
isn't a function. strlen
is, but you probably shouldn't call it in a loop - b1
's length won't change on us, will it? Also, it returns a size_t
, which may be the same size as int
on your platform but will be unsigned. This can (but usually won't) cause errors, but you should do it right anyway.a1
only has enough space for the first string, because the compiler doesn't know to allocate extra stack space for the rest of the string since. If you provide an explicit size, like [100]
, that should be enough for your purposes. If you need robust code that doesn't make assumptions about what is "enough", you should look into malloc
and friends, though that may be a lesson for another day.i < b1_len
(assuming you have a variable, b1_len
, that was set to the length of b1
before the loop began) would be sufficient - strlen
doesn't count the '\0'
at the end.'\0'
at the end, a slightly more efficient implementation could use sizeof a1 - 1
instead of strlen(a1)
in this case, since a1
(and b1
) are declared as arrays, not pointers. It's your choice, but remember that sizeof
won't work for pointers, so don't get them mixed up.char *p = malloc(/*some*/); p = /* something */
is a problem. =
with pointers doesn't copy contents, it copies the value, so you're throwing away the old pointer value you got from malloc
. To copy the contents of a string into a char *
(or a char []
for that matter) you'd need to use strcpy
, strncpy
, or (my preference) memcpy
. (Or just a loop, but that's rather silly. Then again, it may be good practice if you're writing your own strcat
.)malloc
, but that's a religious war and we don't need one of those.If you have strdup
, use it. If you don't, here is a working implementation:
char *strdup(const char *c)
{
size_t l = strlen(c);
char *d = malloc(l + 1);
if(d) memcpy(d, c, l + 1);
return d;
}
It is one of the most useful functions not in the C standard library.