How to concat two char * in C?

后端 未结 3 390
谎友^
谎友^ 2021-01-11 14:19

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{
            


        
3条回答
  •  不要未来只要你来
    2021-01-11 14:54

    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;
    

提交回复
热议问题