如何在C中动态扩展字符串

sa1*_*125 6 c string malloc

我有一个函数可以递归地对一组数字进行一些计算。我还想通过传递前一个计算中的字符串并将其与当前操作连接来漂亮地打印每个递归调用中的计算。示例输出可能如下所示:

3
(3) + 2
((3) + 2) / 4
(((3) + 2) / 4) x 5
((((3) + 2) / 4) x 5) + 14
... and so on
Run Code Online (Sandbox Code Playgroud)

所以基本上,第二次调用得到 3 并附加 + 2,第三次调用得到传递 (3) + 2 等等。我的递归函数原型如下所示:

void calc_rec(int input[], int length, char * previous_string);
Run Code Online (Sandbox Code Playgroud)

我编写了 2 个辅助函数来帮助我进行操作,但是当我测试它们时它们会崩溃:

/**********************************************************************
 * dynamically allocate and append new string to old string and return a pointer to it
 **********************************************************************/
 char * strapp(char * old, char * new)
 {
     // find the size of the string to allocate
     int len = sizeof(char) * (strlen(old) + strlen(new));

     // allocate a pointer to the new string
     char * out = (char*)malloc(len);

     // concat both strings and return
     sprintf(out, "%s%s", old, new);

     return out;
 }

/**********************************************************************
 * returns a pretty math representation of the calculation op
 **********************************************************************/
 char * mathop(char * old, char operand, int num)
 {
     char * output, *newout;
     char fstr[50]; // random guess.. couldn't think of a better way.
     sprintf(fstr, " %c %d", operand, num);
     output = strapp(old, fstr);
     newout = (char*)malloc( 2*sizeof(char)+sizeof(output) );
     sprintf(newout, "(%s)", output);
     free(output);
     return newout;  
 }


void test_mathop()
{
    int i, total = 10;
    char * first = "3";
    printf("in test_mathop\n");
    while (i < total)
    {
        first = mathop(first, "+", i);
        printf("%s\n", first);
        ++i;
    }
}
Run Code Online (Sandbox Code Playgroud)

Strapp() 返回一个指向新附加字符串的指针(有效),而 mathop() 应该采用旧的计算字符串("(3)+2")、一个字符操作数('+'、'-' 等)和一个int,并返回一个指向新字符串的指针,例如“((3)+2)/3”。知道我在哪里搞砸了吗?谢谢。

cod*_*ict 2

我看到的一个迫在眉睫的问题是:

int len = sizeof(char) * (strlen(old) + strlen(new));
Run Code Online (Sandbox Code Playgroud)

不为NULL末尾的字符分配空间。所以你需要分配一个额外的字符。