【发布时间】:2010-03-18 08:45:57
【问题描述】:
我有一个函数可以递归地对一组数字进行一些计算。我还想通过传递上一个计算中的字符串并将其与当前操作连接来漂亮地打印每个递归调用中的计算。示例输出可能如下所示:
3
(3) + 2
((3) + 2) / 4
(((3) + 2) / 4) x 5
((((3) + 2) / 4) x 5) + 14
... and so on
所以基本上,第二个调用得到 3 并附加 + 2 ,第三个调用得到传递 (3) + 2 等等。我的递归函数原型如下所示:
void calc_rec(int input[], int length, char * previous_string);
我写了 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;
}
}
strapp() 返回一个指向新添加的字符串(有效)的指针,而 mathop() 应该采用旧的计算字符串 ("(3)+2"),一个 char 操作数 ('+', '-' , etc) 和一个 int,并返回一个指向新字符串的指针,例如“((3)+2)/3”。知道我在哪里搞砸了吗?谢谢。
【问题讨论】:
-
sizeof(output) 将为您提供指针的大小。与 strlen 非常不同。
-
你还没有初始化i!!
-
您可能应该删除 sizeof (char),它只是一种写 1 的大写方式,会使事情变得混乱并且(最坏的情况)会增加混乱。
-
@Agnel 为什么不添加这些作为答案?我会说你应该得到一些 + 的观察结果:-)
-
@Péter Török - 我对这些回复不太自信。但你说得有道理……