簡體   English   中英

如何在C中連接兩個char *?

[英]How to concat two char * in C?

我收到一個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
}

像這樣的東西:

  real[i].buffer += buffer;

我怎么能在C中這樣做?

通常,請執行以下操作(根據需要調整並添加錯誤檢查)

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

您可以使用strcat(3)來連接字符串。 確保您在目的地分配了足夠的空間!

請注意,只是多次調用strcat()將導致Schlemiel成為Painter的算法 跟蹤您的結構(或其他地方,如果您願意)的總長度將幫助您解決這個問題。

我不清楚。 你想要:

  • 將您收到的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM