Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 *.

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 ?

like image 565
Valter Silva Avatar asked Mar 17 '12 02:03

Valter Silva


1 Answers

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;
like image 134
Java42 Avatar answered Sep 21 '22 09:09

Java42