如何在C中连接两个char*?

Val*_*lva 9 c pointers concatenation

我收到一个char*缓冲区,其长度为10.但是我想在我的struct中连接整个内容,它们有一个变量char*.

typedef struct{
    char *buffer;
  //..

}file_entry;

file_entry real[128];

int fs_write(char *buffer, int size, int file) {
   //every time this function is called buffer have 10 of lenght only
   // I want to concat the whole text in my char* in my struct
}
Run Code Online (Sandbox Code Playgroud)

像这样的东西:

  real[i].buffer += buffer;
Run Code Online (Sandbox Code Playgroud)

我怎么能在C中这样做?

Jav*_*a42 11

通常,请执行以下操作(根据需要调整并添加错误检查)

// real[i].buffer += buffer; 

   // Determine new size
   int newSize = strlen(real[i].buffer)  + strlen(buffer) + 1; 

   // Allocate new buffer
   char * newBuffer = (char *)malloc(newSize);

   // do the copy and concat
   strcpy(newBuffer,real[i].buffer);
   strcat(newBuffer,buffer); // or strncat

   // release old buffer
   free(real[i].buffer);

   // store new pointer
   real[i].buffer = newBuffer;
Run Code Online (Sandbox Code Playgroud)