2012-03-17 71 views
8

我收到一个长度为10的char *缓冲区。 但是我想要将我的结构中包含变量char *的整个内容连接起来。如何在C中连接两个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?

回答

10

在一般情况下,请执行下列操作(调整,并添加错误检查您认为合适的)

// 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; 
4

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

请注意,只需拨打strcat()一堆将导致Schlemiel the Painter's algorithm。跟踪你的结构(或其他地方,如果你喜欢的话)的总长度可以帮助你解决这个问题。

+0

始终使用'strncat'(也包含在上面的链接中)而不是'strcat'。 – pickypg 2012-03-17 02:59:11

+3

总是?这似乎有点严重。 “小心”总是很好的建议,但我会同意这一点。以下是关于何时使用每个问题的一个问题和一些答案:http://stackoverflow.com/questions/6491038/strcat-vs-strncat-when-should-which-function-be-used – 2012-03-17 03:00:16

+2

如果你不知道你为什么使用'strcat',这是因为两个缓冲区都在预定的保证下,所以你应该总是使用'strncat'。从C开始的人总是比'strcat'更好地使用'strncat',因为风险不值得那么不值得注意。考虑到实际的好处,我甚至会争辩说,除非你写的东西低得令人难以置信,而且先决条件已经完成,否则你永远不会从中受益。 – pickypg 2012-03-17 15:57:32

0

我不清楚。你想:

  • 来连接您收到到一个数组中的10个字符缓冲区中的每一个,在指出一个real[0].buffer,或
  • 你想在一个不同的real[i].buffer必须指出每10个字符缓冲区,或
  • 别的东西?

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

#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);