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

C语言readAllRecipes函数触发段错误,输入int值后printf打印无输出

段错误诱因

核心问题是访问了未初始化的野指针:

  • 你仅通过malloc申请了numRecipes个recipe*类型指针的存储空间,数组内的每个theRecipes[i]指针都属于未初始化的野指针,没有指向合法的recipe结构体内存空间
  • 执行scanf("%d", &theRecipes[i]->numItems)时,直接对野指针theRecipes[i]做解引用操作访问numItems成员,尝试往非法内存地址写入输入的数值,直接触发段错误,这也是后续printf语句完全不会执行的直接原因。
    此外还存在逻辑顺序错误:你原本需要拿输入的numItems值作为参数调用readRecipe获取recipe结构体指针,但现有写法是先尝试把值存到还不存在的recipe结构体成员里,逻辑完全颠倒。

修复方案

你需要先定义临时变量存储输入的numItems数值,再把这个数值传给readRecipe获取合法的recipe结构体指针,赋值给theRecipes[i]即可,修复后的代码如下:

recipe** readAllRecipes(int numRecipes)
 {
   recipe** theRecipes = malloc(sizeof(recipe *) * numRecipes);
   // 新增malloc失败判空,避免后续操作异常
   if (theRecipes == NULL) {
       return NULL;
   }
   int i;

   for(i = 0; i < numRecipes; i++)
   {
    // 定义临时变量存储输入的数值
    int numItems;
    scanf("%d", &numItems);
    
    printf("\n\n\t\t here in readAll for loop\n");
    
    // 传入临时变量调用readRecipe,获取合法的结构体指针
    theRecipes[i] = readRecipe(numItems);
   }

   return theRecipes;
}

内容的提问来源于stack exchange,提问作者Maysa G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:36:02