Concatenation in C
strcat appends at the existing terminator, so the target must have room for both.
#include <string.h>
void join_three(char *out, size_t cap, const char *a, const char *b,
const char *c) {
if (cap == 0) {
return;
}
out[0] = '\0';
size_t used = 0;
const char *parts[3] = {a, b, c};
for (int i = 0; i < 3; i++) {
size_t n = strlen(parts[i]);
if (used + n + 1 > cap) {
break;
}
memcpy(out + used, parts[i], n + 1);
used += n;
}
}
How it works
- The destination needs space for its own length plus the source plus one.
- Repeated
strcatrescans from the start each time, which is quadratic. - Tracking the end yourself turns it back into linear work.
Keywords and builtins used here
breakcharconstforifintjoin_threereturnsize_tvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 345
- Tokens
- 134
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 85 seconds.
Step 3 of 4 in Copying & building, step 3 of 13 in Strings & text.