Prepending to a string

后端 未结 8 2074
北荒
北荒 2020-12-09 01:49

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.

相关标签:
8条回答
  • 2020-12-09 02:47

    Copying can hardly be avoided if you want it in the same memory chunk. If the allocated chunk is large enough you could use memmove to shift the original string by the length of what you want to prepend and then copy that one into the beginning, but I doubt this is less "clunky". It would however save you extra memory (again, granted that the original chunk has enough free space for them both).

    Something like this:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    void prepend(char* s, const char* t);
    
    /* Prepends t into s. Assumes s has enough space allocated
    ** for the combined string.
    */
    void prepend(char* s, const char* t)
    {
        size_t len = strlen(t);
        memmove(s + len, s, strlen(s) + 1);
        memcpy(s, t, len);
    }
    
    int main()
    {
        char* s = malloc(100);
        strcpy(s, "file");
        prepend(s, "dir/");
    
        printf("%s\n", s);
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-09 02:47

    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.

    0 讨论(0)
提交回复
热议问题