我刚刚意识到我正在编写的程序存在一个重大缺陷。它是一个象征性地区分数学函数的程序,例如, "x^2+5"
- > "2*x"
,所涉及的主函数就像
char * deriveFromTree ( node * rt )
{
char * dfdx = malloc(100*sizeof(char)); // buffer
if (rt->op) // if rt is of the form rt = gx op hx
{
char * dgdx = deriveFromTree(rt->gx); // g'(x)
char * dhdx = deriveFromTree(rt->hx); // h'(x)
char thisop = *rt->op;
if (thisop == '+' || thisop == '-')
{
// ADDITION/SUBTRACTION RULE:
// dfdx = dgdx + thisop + dhdx
dfdx = strcat(dfdx, dgdx);
dfdx = strcat(dfdx, charToString(thisop));
dfdx = strcat(dfdx, dhdx);
}
正如您可能已经看到的那样,问题是deriveFromTree
的结果适合长度为100
的缓冲区,但结果也是由其他几个结果组成的,这些结果刚刚赢得&#39工作。另一种解决方案是删除缓冲区并将dfdx
设置为所需的确切长度:
char * deriveFromTree ( node * rt )
{
char * dfdx;
if (rt->op) // if rt is of the form rt = gx op hx
{
char * dgdx = deriveFromTree(rt->gx); // g'(x)
char * dhdx = deriveFromTree(rt->hx); // h'(x)
char thisop = *rt->op;
if (thisop == '+' || thisop == '-')
{
// ADDITION/SUBTRACTION RULE:
// dfdx = dgdx + thisop + dhdx
dfdx = malloc(strlen(dgdx) + strlen(dhdx) + 2);
dfdx = strcat(dfdx, dgdx);
dfdx = strcat(dfdx, charToString(thisop));
dfdx = strcat(dfdx, dhdx);
}
但这是低效的,因为调用strlen(dgdx)
和strlen(dhdx)
遍历字符串dgdx
和dhdx
,然后在strcat
中再次迭代它们调用。
这个问题的最佳解决方案是什么?
答案 0 :(得分:1)
由于您已将问题标记为c ++,我建议使用chuck char *并使用std :: string。 代码如下所示:
string deriveFromTree ( node * rt )
{
string dfdx // buffer
if (rt->op) // if rt is of the form rt = gx op hx
{
string dgdx = deriveFromTree(rt->gx); // g'(x)
string dhdx = deriveFromTree(rt->hx); // h'(x)
char thisop = *rt->op;
if (thisop == '+' || thisop == '-')
{
// ADDITION/SUBTRACTION RULE:
// dfdx = dgdx + thisop + dhdx
dfdx = dfdx + dgdx + thisop + dhdx; //strcat(dfdx, dgdx);
}