Search code examples
cstringcrtconcatenationstrcat

Concatenating C strings in linear time with crt


Say we want to concatenate const char *s[0], s[1], ... s[n-1] into one long char out[] in C.

Formally (ignoring buffer overruns, for simplicity):

void concatManyStrings(char out[], const char *s[], size_t n);

It is a trivial task, of course: start with a pointer to out and advance it for every char,
while looping through the input strings.

Another approach (which is still linear-time) would be to keep a pointer to the end,
and with each s[i] do:

{ strcpy(endp, s[i]); endp += strlen(s[i]); }

But, the code would be cleaner if there was a standard CRT function that knows how to strcpy(),
and return the number of copied chars (or equivalently, a pointer to the next char after the copied).

The only CRT function I can think of that does that is sprintf(), but it is obviously not nearly
as efficient as a simple strcpy() that returns count.

Is there such a function that I'm missing?


Solution

  • strlcpy() and strlcat() are non-standard, unfortunately, but if you happen to have them, you can use them for this. They both return results that let you determine the end of the copied string, unlike strcpy() and strcat() which (somewhat uselessly) return a pointer to the start of the destination.