What is the most efficient way to prepend to a C string, using as little memory as possible?
I am trying to reconstruct the path to a file in a large directory tree.
Perhaps I'm confused, but I believe that a prepend is the same as appending with the strings swapped. So instead of prepending "Hello" to "World", the string "World" can be appended to "Hello":
const char world[] = "World";
const char hello[] = "Hello";
// Prepend hello to world:
const unsigned int RESULT_SIZE = sizeof(world) + sizeof(hello) + 2 * sizeof('\0');
char * result = malloc(RESULT_SIZE);
if (result)
{
strcpy(result, hello);
strcat(result, world);
puts("Result of prepending hello to world: ");
puts(result);
puts("\n");
}
Also, the main waste of execution time is finding the end of a string. If the strings were stored with the length, the end could be calculated faster.