简体   繁体   English

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

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

I receive a char * buffer which have the lenght of 10. But I want to concat the whole content in my struct which have an variable char *. 我收到一个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
}

Something like this : 像这样的东西:

  real[i].buffer += buffer;

How can I do this in C ? 我怎么能在C中这样做?

In general, do the following (adjust and add error checking as you see fit) 通常,请执行以下操作(根据需要调整并添加错误检查)

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

You can use strcat(3) to concatenate strings. 您可以使用strcat(3)来连接字符串。 Make sure you have allocated enough space at the destination! 确保您在目的地分配了足够的空间!

Note that just calling strcat() a bunch of times will result in a Schlemiel the Painter's algorithm . 请注意,只是多次调用strcat()将导致Schlemiel成为Painter的算法 Keeping track of the total length in your structure (or elsewhere, if you prefer) will help you out with that. 跟踪您的结构(或其他地方,如果您愿意)的总长度将帮助您解决这个问题。

I am not clear. 我不清楚。 Do you want: 你想要:

  • to concatenate every one of the 10 character buffers you receive into one array, pointed at by one real[0].buffer , or 将您收到的10个字符缓冲区中的每一个连接到一个数组中,由一个real[0].buffer ,或者
  • do you want each 10 character buffer to be pointed at by a different real[i].buffer , or 你想让每个10个字符的缓冲区由不同的real[i].buffer ,或者
  • something else? 别的什么?

You will need to allocate enough space for the copy of the 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