How to concat two char * in C?

后端 未结 3 391
谎友^
谎友^ 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:53

    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
    • do you want each 10 character buffer to be pointed at by a different real[i].buffer, or
    • something else?

    You will need to allocate enough space for the copy of the buffer:

    #include 
    //...
    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);
    

提交回复
热议问题