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

为什么在C语言helper函数getInput中解引用指针会导致程序终止

问题原因及修复方案

1. 直接崩溃的核心原因

你有两个指针相关的低级错误直接导致解引用非法地址崩溃:

  • main函数中定义指针的代码错误:int *ptr = recordsRead; 是把recordsRead的当前值0直接赋值给指针,相当于ptr指向了内存地址0,属于用户态不可访问的非法地址,后续解引用直接触发段错误。正确写法应该是取变量地址:int *ptr = &recordsRead;
  • 调用getInput时传参类型错误:getInput第二个参数要求传入int*类型的指针,但你传的是recordsRead这个int类型的数值,相当于把变量值当地址传入函数,函数内部执行*n = temp时就是访问非法地址,直接崩溃。正确写法应该传入地址:getInput(list, &recordsRead);

2. 其他逻辑错误修复

除了崩溃问题,你的代码还有多处功能逻辑错误:

  • getInput中存储数据永远只写list[0],没有偏移,多条记录会互相覆盖。需要每次写入list[temp],且要加边界判断避免数组越界:
// 修正后的getInput核心逻辑
void getInput(leaveRecord list[ ], int *n){
    int option = 0, temp = 0;
    int userInput;
    while (option == 0 && temp < SIZE) {
        printf("Please key in the Staff Identifier:\n");
        scanf("%d", &list[temp].id);
        printf("Please key in the Total Number of Days allowed:\n");
        scanf("%d", &list[temp].totalLeave);
        printf("Please key in the Number of Days of Leave taken:\n");
        scanf("%d", &list[temp].leaveTaken);
        temp += 1;
        printf("Please Key in 1 if you like to stop adding Records:\n");
        scanf("%d", &userInput);
        if(userInput == 1){
            break;
        }
    }
    *n = temp;
}
  • mayTakeLeave逻辑错误:
    1. 只访问list[0]的内容,没有遍历整个数组
    2. 第一个元素不匹配就直接返回-1,不会遍历后续元素
    3. leaveUsed计算位置错误,应该匹配到对应员工后再计算
      修正后代码:
int mayTakeLeave(leaveRecord list[ ], int id, int leave, int n){
    for(int i = 0; i < n; i++){
        if(list[i].id == id){
            int leaveUsed = leave + list[i].leaveTaken;
            return leaveUsed <= list[i].totalLeave ? 1 : 0;
        }
    }
    return -1; // 遍历完所有记录都没找到才返回员工不存在
}
  • printList的printf用法完全错误,需要逐个打印结构体字段:
void printList(leaveRecord list[ ], int n){
    for(int i = 0; i < n; i++){
        printf("员工ID:%d,总休假额度:%d,已休假:%d\n", list[i].id, list[i].totalLeave, list[i].leaveTaken);
    }
}
  • main函数的循环条件错误,你写的while (choice <3)会导致选3、4都直接退出,无法触发printList功能,应该改成while (choice !=4)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:54:00