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

时间:2012-03-17 02:56:58

标签: c pointers concatenation

我收到一个长度为10的char *缓冲区。 但是我想在我的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
}

这样的事情:

  real[i].buffer += buffer;

我怎样才能在C中做到这一点?

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:4)

您可以使用strcat(3)来连接字符串。确保在目的地分配了足够的空间!

请注意,只是多次调用strcat()会产生Schlemiel the Painter's algorithm。跟踪您的结构(或其他地方,如果您愿意)的总长度将帮助您解决这个问题。

答案 2 :(得分:0)

我不清楚。你想要吗:

  • 将您收到的10个字符缓冲区中的每一个连接到一个数组中,由一个real[0].buffer指向,或
  • 您希望每个10个字符缓冲区由不同的real[i].buffer
  • 指向
  • 别的什么?

您需要为缓冲区的副本分配足够的空间:

#include <stdlib.h>
//...
int size = 10+1; // need to allocate enough space for a terminating '\0'
char* buff = (char *)malloc(size);   
if (buff == NULL) {
    fprintf(stderr, "Error: Failed to allocate %d bytes in file: %s, line %d\n,
                     size, __FILE__, __LINE__ );
    exit(1);
}
buff[0] = '\0';    // terminate the string so that strcat can work, if needed
//...
real[i].buffer = buff;  // now buffer points at some space
//...
strncpy(real[i].buffer, buffer, size-1);