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

C语言malloc分配数组后scanf存入值为垃圾值问题求助

问题代码错误点修复说明
  • 该问题和VSCode环境无关,完全是代码语法与逻辑错误导致的异常。
  • 核心字符比较语法错误:C语言中char类型的字符常量需要用单引号'包裹,你代码中用双引号"包裹的"P"/"p"/"G"/"g"本质是字符串常量(指向字符数组的指针),和char类型的tamanhos[i]比较逻辑永远不成立,会导致统计逻辑完全失效。
  • 数组显示垃圾值的正常性说明:malloc分配的堆内存默认不会初始化,未赋值前存储的是随机垃圾值,只有循环执行到对应下标完成赋值后,该位置的内容才会更新为你输入的有效值,调试时如果在循环未完成时查看数组,未赋值的位置自然显示为垃圾值,属于正常现象。
  • 打印顺序错误:你第一次打印total的代码写在统计逻辑之前,此时total还是初始值0,无法输出正确的统计结果。
  • 硬编码维护性问题:你已经用#define定义了professores为7,后续循环中直接写死7的写法不利于后续维护,建议统一替换为宏定义。

修复后完整代码

#include <stdio.h>
#include <stdlib.h>
#define professores 7
int main () {
    int quantidade, total, holder;
    char tamanho;

    total = 0;

    int * quantidades = (int*)malloc(professores*sizeof(int));
    char * tamanhos = (char*)malloc(professores*sizeof(char));
    // 新增内存分配失败判断,养成健壮编码习惯
    if (quantidades == NULL || tamanhos == NULL) {
        printf("内存分配失败\n");
        return 1;
    }

    for (int i = 0; i < professores; i++){
        scanf(" %d", &quantidade);
        scanf(" %c", &tamanho);
        quantidades[i] = quantidade;
        tamanhos[i] = tamanho;
    }

    for (int i = 0; i < professores; i++ ){
        // 双引号修改为单引号匹配char类型比较
        if (tamanhos[i] == 'P' || tamanhos[i] == 'p') {
            holder = quantidades[i];
            total = total + quantidades[i]*10;
        }
        else if (tamanhos[i] == 'G' || tamanhos[i] == 'g') {
            total = total + quantidades[i]*16;
        }
    }
    printf("%d\n", total);
    int xprof = total / professores;
    printf("%d", xprof);

    free(quantidades);
    free(tamanhos);

    return 0;
}

内容的提问来源于stack exchange,提问作者JOAO VITOR PEREIRA VENTURA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:12:03