So i want to have a struct called poly_el which stores the value of the coefficient and power of a polynomial element (for eg 3x^4 will be stored as 3 and 4 in the struct). I want these to be of type double of course. Eventually I wish to make a linked list of such elements to represent a whole polynomial. So I am using a pointer to the struct and for some reason the pointer just returns 0 instead of the values i am assigning to it.
Here is the gist of the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
struct poly_el {
double coeff;
double power;
struct poly_el *next;
};
int main() {
double a=10.0;
double b=20.0;
struct poly_el *spe;
spe=(struct poly_el *)malloc(sizeof(struct poly_el));
spe->coeff=a;
spe->power=b;
printf("%f coeff, %f power", &spe->coeff, &spe->power);
}
I expect it to output 10 coeff, 20 power but it just outputs 0.000 for both. Also, I have tried %lf,%ld instead of %f and also tried doing the same code but with floats. None of these have seemed to work. I feel there is some kind of an error in my assignment of a and b spe->coeff and power.
CodePudding user response:
The problem is that you pass by reference the variables spe->coeff and spe->power, while you want to print the values, so just get rid of symbol & in your printf, like :
printf("%f coeff, %f power", spe->coeff, spe->power);
remember that pointing a variable by reference gives you the address of that variable in memory.