2012-03-17 47 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);