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

基础C语言数组操作代码报错Error -1073741819,求排查

问题分析与修复

错误码0xC0000005是Windows下的内存访问违规错误,你的代码里有几个关键问题直接导致了崩溃,逐一拆解:

核心错误点

  • scanf用法完全错误:
    • 你用了%s格式符读取字符串,但变量acted、acc、am都是int类型,类型不匹配;
    • scanf读取基本类型时必须传递变量的地址(用&符号),直接传变量名会把变量的当前值当作内存地址写入,必然触发内存访问违规。
  • printf格式缺失:查询余额的分支里,printf没有写格式符%d,根本不会输出账户号和余额。
  • 数组未初始化:局部数组account[1000]的初始值是随机垃圾值,操作前需要初始化为0。
  • 循环逻辑不合理:用for(q=0;q<100000;++q)不是真正的无限循环,应该用while(1)实现持续交互。
  • 无索引越界检查:输入的账户号如果超过999,会导致数组越界访问,同样可能触发崩溃。

修正后的代码

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

int main()
{
    // 初始化数组所有元素为0
    int account[1000] = {0};
    // 选项提示
    printf("Check balance : 3\n");
    printf("Add cash : 2\n");
    printf("Remove cash : 1\n");

    // 真正的无限循环,直到用户主动退出
    while(1){
        printf("\nSelect Action: ");
        int acted;
        // 读取整数,传递变量地址
        scanf("%d", &acted);

        printf("Enter account number: ");
        int acc;
        scanf("%d", &acc);

        // 检查账户号是否合法
        if(acc < 0 || acc >= 1000){
            printf("Invalid account number! Must be between 0 and 999.\n");
            continue;
        }

        // 分支逻辑修正
        if (acted == 1) {
            printf("Amount of cash to remove: ");
            int am;
            scanf("%d", &am);
            // 可选:检查余额是否足够
            if(account[acc] < am){
                printf("Insufficient balance!\n");
                continue;
            }
            account[acc] -= am;
            printf("Success! New balance: %d\n", account[acc]);
        } else if(acted == 2) {
            printf("Amount of cash to add: ");
            int am;
            scanf("%d", &am);
            // 可选:检查金额是否为正
            if(am <= 0){
                printf("Invalid amount! Must be positive.\n");
                continue;
            }
            account[acc] += am;
            printf("Success! New balance: %d\n", account[acc]);
        } else if(acted == 3) {
            printf("Account Number: %d\n", acc);
            printf("Balance of account: %d\n", account[acc]);
        } else {
            printf("Invalid action! Please enter 1, 2, or 3.\n");
        }
    }
    return 0;
}

额外优化说明

  • 加了账户号合法性检查,避免数组越界;
  • 增加了金额有效性检查(比如取款不能超过余额,存款金额为正);
  • 优化了输出提示,让交互更清晰;
  • 用while(1)实现真正的无限循环,用户可以通过Ctrl+C终止程序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:27:23