This question already has answers here:
How do I concatenate the string elements of my array into a single string in C?
                                
                                    (3个答案)
                                
                        
                                去年关闭。
            
                    
将给定的char *input[]转换为具有单个空格的行

输入:

int n =3;
char *result;
char *input[]= {"one", "two", "three" };
result = convertToLine(n, input)




char *convertToLine(int n, char *input[]) {
    int size = n* 2;
    char* string = (char*)malloc(sizeof(char)*size);
    int i = 0;
    int k = 0;
    while (i <size){
        string[i] = *input[k];
        string[i+1] = ' ';
        i++;
        k++;
     }
   string[n] = '\0';
   return string;
}


我的输出:
空值

预期产量:

result = "one two three"

最佳答案

如果我理解您的问题,那么您的问题是您无法分配字符串,例如

string[i] = *input[k];


在上面,您尝试将第k个指针的第一个字符分配给string[i],该字符将读取到input的末尾。它等效于:

*(input[k] + 0)


要么

input[k][0]


参见:C Operator Precedence

相反,您需要调用strcpy或简单地使用附加循环来复制每个所需的字符,例如

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

char *convertToLine (size_t n, char *input[])
{
    size_t  ndx = 0,        /* string index */
            len = 0;        /* length of combined strings */
    char *string = NULL;    /* pointer to string */

    for (size_t i = 0; i < n; i++)  /* length of all in input */
        len += strlen (input[i]);

    string = malloc (len + n);      /* allocate len + n-1 space + 1 */
    if (!string) {                  /* validate allocation */
        perror ("malloc-string");
        return NULL;
    }
    for (size_t i = 0; i < n; i++) {        /* for each string */
        if (i)                              /* if not 1st */
            string[ndx++] = ' ';            /* add space */
        for (int j = 0; input[i][j]; j++)   /* copy input string */
            string[ndx++] = input[i][j];
    }
    string[ndx] = '\0';     /* nul-terminate */
    return string;
}


在您的input中添加一个简短示例,您将拥有:

int main (void) {
    char *input[]= {"one", "two", "three" },
        *result = NULL;
    size_t n = sizeof input / sizeof *input;

    result = convertToLine (n, input);
    if (result) {
        printf ("result: '%s'\n", result);
        free (result);
    }
}


使用/输出示例

$ ./bin/str_combind
result: 'one two three'

09-04 16:36