指向结构的指针的元素只返回 0

elements of a pointer to a struct just returning 0

所以我想要一个名为 poly_el 的结构,它存储多项式元素的系数值和幂(例如,3x^4 将在结构中存储为 3 和 4)。我当然希望这些是双精度类型。最终我希望制作一个包含这些元素的链表来表示整个多项式。所以我使用了一个指向结构的指针,出于某种原因,指针只是 returns 0 而不是我分配给它的值。

代码的要点如下:

#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);
}

我希望它输出 10 系数和 20 次方,但两者都只输出 0.000。此外,我已经尝试使用 %lf,%ld 而不是 %f 并且还尝试使用浮点数执行相同的代码。 None 其中似乎有效。我觉得我对 a 和 b spe->coeff 和 power 的分配有某种错误。

问题是您通过引用传递了变量 spe->coeff 和 spe->power,而您想要打印这些值,所以只需去掉 printf 中的符号 &,例如:

printf("%f coeff, %f power", spe->coeff, spe->power);

请记住,通过引用指向变量会为您提供该变量在内存中的地址。