不能通过c中的另一个字符串连接字符串

can't concat strings via another string in c

例如

array = ["abc", "def", "xx"] , concat_string = "-"

output: "abc-def-xx"

我得到了"abc-"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifndef STRUCT_STRING_ARRAY
#define STRUCT_STRING_ARRAY
typedef struct s_string_array
{
    int size;
    char** array;
} string_array;
#endif


char* my_join(string_array* param_1, char* param_2)
{
    int len = param_1->size;
    if(len == 0){
        return NULL;
    }

    char **my_arr = param_1->array;
    int total_len = 0;//this is to create array that will store the entire string , i need total length to know how much malloc to do

    for(int i = 0 ; i < len;i++){
        total_len += strlen(my_arr[i]) + strlen(param_2);
    }

    char *res;
    //char res[total_len];//tried this but it did not work
    for(int i = 0; i < len-1;i++){
        strncat(my_arr[i], param_2, 1);//concat the string- add param_2 to my-arr
        strncat(res, my_arr[i],1); //concat every my_arr to res
    }

    return res;
}


int main(){

    struct s_string_array s= {
        .size = 3,
        .array = (char*[]){"abc", "def", "gh"}

    };

    char *t = "-";

    my_join(&s,t);
    return 0;
}

为什么停在 "abc"?

要修复未初始化的指针和分配问题,您可以使用 malloc()res 分配内存(不要忘记验证分配),然后将 res 初始化为空字符串,并按如下方式调整连接:

char* my_join(string_array* param_1, char* param_2)
{
    int len = param_1->size;
    if(len == 0){
        return NULL;
    }

    char **my_arr = param_1->array;
    int total_len = 0;

    for(int i = 0 ; i < len;i++){       /* if param_2 greater than 1-char, you over-allocate */
        total_len += strlen(my_arr[i]) + strlen(param_2);
    }

    char *res = malloc (total_len);     /* allocate / validate */
    if (!res) {
        perror ("malloc-res");
        return NULL;
    }
    *res = 0;                           /* make res empty-string */

    for (int i = 0; i < len; i++) {
        strcat (res, my_arr[i]);        /* concatenate my_arr[i] */
        if (i < len-1)                  /* if not end */
            strcat (res, param_2);      /* concatenate param_2 */
    }

    return res;
}

另请注意 strncat(my_arr[i], param_2, 1); 调用 未定义的行为 。您使用 compound 文字来转换为指针数组,但初始化是使用 string-literals -- 它们的内容无法更改。