将星号传递到c中的字符串

时间:2017-12-06 22:58:32

标签: c string concatenation dynamic-memory-allocation

我有一个问题,即将*放入一个连接的字符串并打印出星号。我的代码需要2个参数字符串,并且需要返回一个指针,即第一个字符串和第二个字符串连接 BUT 我需要它在每个字符之间有*。 (例如:字符串1:09876;字符串2; 12345结果; 0 * 9 * 8 * 7 * 6 * 1 * 2 * 3 * 4 * 5);我的问题不是试图打印这个结果,而是添加星号,特别是因为C不会让我只声明一个*或者指针指向*。所以我有点卡住了。这是我的代码

foo().then(function(result) {
    console.log("result => " + result);
}).catch(function(error) {
    console.log("error => " + error);
});

我只提供了我的功能,因为这是我的代码中唯一的部分我遇到了问题。编辑:我的Malloc中的29是为了记住星号和NULL字符(参数字符串最多有30个字符)我修复了由于社区而添加星号的问题,现在我得到了分段错误,这应该好玩。

1 个答案:

答案 0 :(得分:1)

asterix并不需要成为指针,它只是一个字符。

分配结果字符串时,您没有使用正确的大小。它需要为两个原始字符串中的每个字符分别使用2个字符 - 对于您要复制的每个字符,每个字符为1个字符,其间为星号为1个字符。

您需要在最终结果中添加空终止符。这可以取代最后的星号,因为你只需要在字符之间使用星号,而不是在每个字符之后。

char* widen_stars(char * str1, char *str2)
{       
    int ls1 = strlen(str1);
    int ls2 = strlen(str2);

    char *str4 = (char *) malloc(2 * ls1 + 2 * ls2);
    char *p1 = str1;
    char *p2 = str2;
    char *p3 = str4;
    const char asterix = '*';
    while(*p1 != '\0'){
        *p3++ = *p1++;
        *p3++ = asterix; // Needs to add an *, after printing the first element.//
    }
    while(*p2 != '\0'){
        *p3++ = *p2++;
        *p3++ = asterix;
    }
    // Replace last asterisk with null byte
    if (p3 > str4) {
        p3--;
    }
    *p3 = '\0';
    return str4;
}