Dynamically declaring and defining strings

I am dynamically estimating coefficients of a polynomial whose degree gets progressively larger until some convergence criterion is met: once the estimates are known, the new polynomial is evaluated and checked against the criterion. The evaluation and the convergence criterion is implemented in some external library "polynomial" and my questions have to do with a more dynamic approach in defining the polynomials and its derivative:

#include <stdio.h>
#include "polynomial.h"

#define EQ_SIZE 2048
#define DEGREE 3

int main(int argc, char *argv[]) {
  // coefficients of polynomial and its derivative
  double p[DEGREE] = { 1.0, -2.0, 3.0 };
  double Dp[DEGREE-1];
  for (int i = 1; i < DEGREE; i++) Dp[i-1] = i*p[i];
  char polynomial[EQ_SIZE], derivative[EQ_SIZE];

  // evaluate polynomial and its derivative
  sprintf(polynomial, "%f + %f*x + %f*x*x", p[0], p[1], p[2]);
  evaluate(polynomial, "polynomial");  // the second argument is a label and has no inherent meaning
  sprintf(derivative, "%f + %f*x", q[0], q[1]);
  evaluate(derivative, "derivative");

  return 0;
}
  1. What is a more robust way to declare the degree of the polynomial? Would a variable length-array in combination with malloc() be more efficient?
  2. How could the polynomial itself be more efficiently defined? I am thinking about the following for the i-th term: sprintf(polynomial + strlen(polynomial), "%f * x**%d", p[i], i); where i runs from 0 to DEGREE.
  3. Because I am also evaluating a derivative, the suggestion in question 2 could be refactored in something like the following and which would also require the <string.h> include:
void setterms (char *polynomial, double *p, int degree) {
  sprintf(polynomial, "\0");
  for (int i = 0; i < degree; i++) sprintf(polynomial + strlen(polynomial), "+ (%f * x**%d)", p[i], i);
}

I am using gcc with revision C17.

Hi @technossomy,

Dynamic arrays must always be initialized via malloc() or calloc() resp realloc(). Obviously that's a function call, so this it's less efficient (in the sense of speed) than a static arr[size_const] = ....

Regarding string expansion you could look at e.g. How to dynamically expand a string in C - Stack Overflow

Update: If you're using C++, you should use the string class instead, it's way more comfortable.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.