c - How do I set a buffer in a possibly recursive procedure? -
i realized major flaw in program writing. it's program symbolically differentiates math functions, e.g. "x^2+5"
--> "2*x"
, , master function involved starts off like
char * derivefromtree ( node * rt ) { char * dfdx = malloc(100*sizeof(char)); // buffer if (rt->op) // if rt of 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); }
the problem, might see, result of derivefromtree
fits in buffer of length 100
, result composed of several other results, won't work. alternative solution getting rid of buffer , setting dfdx
exact length needs be:
char * derivefromtree ( node * rt ) { char * dfdx; if (rt->op) // if rt of 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); }
but inefficient because of calls strlen(dgdx)
, strlen(dhdx)
iterate through strings dgdx
, dhdx
, iterated through again in strcat
calls.
what best solution problem?
since have tagged question c++, suggest chuck char * , use std::string. code this:
string derivefromtree ( node * rt ) { string dfdx // buffer if (rt->op) // if rt of 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); }
Comments
Post a Comment