I am trying to initialize dynamically allocated char array to different types within a struct called term, which is a struct that holds parts of a polynomial, (coefficient, var, exponent). The function is a to_string function which returns the struct term as a string of form, "cx^e", or "c" if the term has an exponent of 0.
I believe I have the overall thought process correct for creating the string however I don't know if I'm initializing my char *ptr correctly.
Here's the related code:
The to_string function
char *term_to_string(const term_t *term)
{
char *ptr;
if (term->exponent == 0)
{
ptr = (char *) malloc(sizeof(term->coefficient));
memset(ptr, 'x', sizeof(term->coefficient));
*ptr = term->coefficient;
}
else if (term->coefficient == 1)
{
ptr = (char *) malloc(sizeof (term->var) + sizeof (term->exponent) + sizeof (char));
*ptr = term->var;
*(ptr + 1) = '^';
*(ptr + 2) = term->exponent;
}
else
{
ptr = (char *) malloc(sizeof(term->coefficient) +
sizeof(term->var) +
sizeof(term->exponent) +
sizeof(char));
*ptr = term->coefficient;
*(ptr + 1) = term->var;
*(ptr + 2) = '^';
*(ptr + 3) = term->exponent;
}
return ptr;
}
The struct "term"
typedef struct term
{
int exponent, coefficient;
char var;
} term_t;
Testing the to_string
term_t testterm1 = {1, 'x', 0};
term_t testterm2 = {2, 'x', 1};
term_t testterm3 = {3, 'x', 2};
printf("Testing term.c/h:\n");
printf("testterm1: %s\n", term_to_string(&testterm1));
printf("testterm2: %s\n", term_to_string(&testterm2));
printf("testterm3: %s\n", term_to_string(&testterm3));
I keep getting a segmentation fault error, and I know it has something to do with trying to initialize a NULL pointer. However, I'm confused as to:
1) What size I should allocate the pointer to? (I'm using sizeof(term->coefficient) right now in the first block of my if statement)
2) If I'm properly initializing my pointer? (I used memset in the first block of the if statement but I really don't think I'm using it right at all)
The expected outcome should be
x
2x
3x^2
Any help would be much appreciated!!!
stris uninitialized.strand just returned ptr but it still gives me the same errorsnprintfto format your term (and another call tosnprintfto determine how much space you need to allocate).