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

使用scanf读取hh::mm格式时间输入触发段错误的技术求助

解决你的C语言结构体数组输入段错误问题

嘿,你的代码触发段错误主要是两个小问题导致的,我帮你拆解一下并给出修复方案:

核心问题分析

  1. scanf传参错误:scanf需要接收变量的内存地址才能修改变量的值,但你直接传递了t_time[1].hour和t_time[1].minutes的数值。这就相当于告诉scanf往一个随机的内存位置写数据,操作系统自然会触发段错误阻止非法内存访问。
  2. 数组索引重复:你两次输入都用了t_time[1],这会把第一次输入的时间直接覆盖掉,完全没用到数组的第一个元素t_time[0]。

修复后的完整代码

#include <stdio.h>
struct Time {
    int hour;
    int minutes;
} t_time[2];

int main() {
    puts("Please enter first time in the following format hh::mm\n");
    // 用&取结构体成员的地址,传给scanf
    scanf("%d::%d", &t_time[0].hour, &t_time[0].minutes);
    
    puts("Please enter second time in the following format hh::mm\n");
    scanf("%d::%d", &t_time[1].hour, &t_time[1].minutes);
    
    // 新增输出验证,确认输入是否正确存储
    printf("First saved time: %02d::%02d\n", t_time[0].hour, t_time[0].minutes);
    printf("Second saved time: %02d::%02d\n", t_time[1].hour, t_time[1].minutes);
    
    return 0;
}

关键修复点说明

  • 取地址运算符&:给scanf传递&t_time[0].hour这种形式的地址,让它能准确找到要写入数据的内存位置,这是解决段错误的核心。
  • 正确使用数组索引:C语言数组从0开始计数,所以第一个时间存在t_time[0],第二个存在t_time[1],避免数据覆盖。
  • 可选的健壮性优化:如果想让程序更稳定,可以检查scanf的返回值,确保输入格式符合要求:
    if (scanf("%d::%d", &t_time[0].hour, &t_time[0].minutes) != 2) {
        puts("Error: Invalid input format! Please use hh::mm");
        return 1;
    }
    
    这样如果用户输入格式不对(比如写成12-34),程序会直接提示错误并退出,不会出现后续的异常行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:17:31