You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言结构体指针成员赋值后打印输出始终为0问题求解

故障原因

你代码的赋值逻辑没有问题,问题出在printf的传参错误:你在spe->coeff和spe->power前加了多余的取地址符&,导致传给printf的不是两个double类型的数值,而是这两个成员的内存地址。%f格式符要求传入double类型的参数,类型不匹配触发未定义行为,输出0是该场景下的异常表现,和赋值逻辑无关。

修复方案

删除printf参数中的两个&即可,修改后的对应代码行:

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

可选优化建议

  • 多项式的幂次本质为非负整数,建议将power成员的类型从double改为int,既节省内存也避免浮点数精度问题
  • malloc后需要判断返回值是否为空,避免内存分配失败导致程序崩溃
  • 动态分配的内存使用完成后要调用free释放,避免内存泄漏

优化后的完整可运行代码示例:

#include <stdio.h>
#include <stdlib.h>

struct poly_el {
  double coeff;
  int power;
  struct poly_el *next;
};

int main() {
  double a = 10.0;
  int b = 20;
  struct poly_el *spe = malloc(sizeof(struct poly_el));
  if (spe == NULL) {
    perror("内存分配失败");
    return 1;
  }
  spe->coeff = a;
  spe->power = b;
  printf("%f coeff, %d power\n", spe->coeff, spe->power);
  free(spe);
  return 0;
}

内容的提问来源于stack exchange,提问作者Varun Upamanyu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:54:00