Using strcat in C

后端 未结 7 1665
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 15:50

Okay so I have the following Code which appends a string to another in C#, note that this is Just an example, so giving alternative string concatination met

7条回答
  •  有刺的猬
    2020-12-05 16:24

    The safe way to do this in classic C style is:

     char *strconcat(char *s1, char *s2)
     {
        size_t old_size;
        char *t;
    
        old_size = strlen(s1);
    
        /* cannot use realloc() on initial const char* */
        t = malloc(old_size + strlen(s2) + 1);
        strcpy(t, s1);
        strcpy(t + old_size, s2);
        return t;
      }
    
      ...
    
      char *message = "\n\nHTTP/1.1 ";
      message = strconcat (message, Status_code);
      message = strconcat (message, "\nContent-Type: ");
    

    Now you can say a lot of bad things about it: it's inefficient, it fragments your memory, it's ugly ... but it's more or less what any language with a string concatenation operator and C type (zero-terminated) strings will do (except that most of these languages will have garbage collection built-in).

提交回复
热议问题