I'm trying to implement polynomials in C but Im having an issue with arrays and setting values. Im bad at C, please explain why this is happening: I run this, it says that p.coefs[1]
is 0.0
instead of 3.0
as intended.
#include <stdio.h>
#include <assert.h>
int main()
{
#define MAX_DEG 10
typedef struct Polynomial Polynomial;
struct Polynomial {
int deg;
double coefs[MAX_DEG];
};
Polynomial ply_create(int deg) {
assert(deg >= 0 && deg <= MAX_DEG);
Polynomial poly;
poly.deg = deg;
return poly;
}
void ply_set_coef(Polynomial poly, int i, double val) {
poly.coefs[i] = val;
}
Polynomial p = ply_create(1);
p.coefs[0] = 1.0;
ply_set_coef(p, 1, 3.0);
printf("p.coefs[0] is %f and p.coefs[1] is %f", p.coefs[0], p.coefs[1]);
return 0;
}
I was previously using malloc and made p.coefs a pointer to a double. In this case I did not have any problem.