Consider this simple program that concatenates all specified parameters and prints them in standard output. I used 2 for loops to append the strings, one to calculate the length of that string and one to concatenate the strings. Is there a way doing it with only one loop? It wouldn't be more efficient reallocating memory for each string to concatenate, would it? How would Java's StringBuilder be implemented in C? Would it loop twice as I did?
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char** argv) { size_t len = 0; // start for loop at i = 1 to skip the program name specified in argv for(int i = 1; i < argc; i++) len += strlen(argv[i]) + 1; // +1 for the space char* toAppend = (char*)malloc(len * sizeof(char) + 1); toAppend[0] = '\0'; // first string is empty and null terminated for(int i = 1; i < argc; i++) { strcat(toAppend, argv[i]); strcat(toAppend, " "); } printf(toAppend); free(toAppend); }
strcat, every iteration it goes through the entire string to find the last character, use a moving pointer instead.(char*)malloc(len * sizeof(char) + 1)ismalloc(len + 1).void*doesn’t need to be cast.