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

C语言数组输出异常求助:数组越界及时分分离需求

Fixing Array Out-of-Bounds Output & Proper Time Parsing in C

It sounds like you're hitting undefined behavior from improper string handling—this is super common when working with char arrays in C, especially when parsing time strings. The out-of-bounds output almost always happens because your arrays aren't properly null-terminated, or you're accessing memory beyond what you've allocated. Let's break this down and fix it with a working example that meets your requirement of two separate arrays for hours and the remaining time (without AM/PM).

Common Causes of Your Issue

  • Missing null terminator ('\0'): C strings rely on this character to signal the end. If you forget to add it, the program will keep reading memory past your array until it finds a random '\0', leading to garbage output.
  • Insufficient array/memory size: If your input time string (like "12:34:56 PM") is longer than the space you allocated, writing to it will overflow into adjacent memory.
  • Unchecked index access: Accidentally using an index that's beyond your array's declared length (e.g., an array of size 5 but accessing index 5 or higher).

Working Solution Code

Here's a complete, safe implementation that parses a 12-hour time string into hours and the remaining time (minutes:seconds, no AM/PM):

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

int main() {
    // Example input time string (adjust as needed, or read from user)
    const char* input_time = "09:45:30 AM";
    
    // Allocate arrays: 
    // - Hours array: max 2 digits + null terminator = 3 chars
    // - Remaining time array: up to "MM:SS" + null terminator = 6 chars
    char hours[3];
    char remaining_time[6];
    
    // Extract hours using sscanf (safe and straightforward)
    // The format string captures hours, then the rest before AM/PM
    if (sscanf(input_time, "%2s:%5s %*2s", hours, remaining_time) == 2) {
        // Ensure null termination (sscanf adds it automatically here, but good practice to confirm)
        hours[2] = '\0';
        remaining_time[5] = '\0';
        
        printf("Hours: %s\n", hours);
        printf("Remaining time (no AM/PM): %s\n", remaining_time);
    } else {
        printf("Error: Invalid time format!\n");
        return 1;
    }
    
    // If you prefer malloc instead of stack arrays (like your snippet started with):
    // char* hours = malloc(3 * sizeof(char));
    // char* remaining_time = malloc(6 * sizeof(char));
    // Don't forget to free them later: free(hours); free(remaining_time);
    
    return 0;
}

Key Details in This Code

  1. Safe Parsing with sscanf:
    • %2s reads up to 2 characters for hours (prevents overflow into the hours array).
    • %5s reads up to 5 characters for the MM:SS part (since "MM:SS" is 5 characters long).
    • %*2s skips the AM/PM part (the * means "read but don't store").
  2. Explicit Null Termination: Even though sscanf adds '\0' when using %s, explicitly setting it ensures you don't hit edge cases where the input is exactly the array length.
  3. Proper Array Sizing: The hours array is size 3 (2 digits + '\0'), remaining time is size 6 (5 chars for MM:SS + '\0'). This avoids overflow.

Why Your Original Code Might Be Failing

Looking at your snippet, you started with char* s = (char *)malloc(10 * sizeo...—if that's sizeof(char), 10 bytes is enough for most time strings, but if you're not null-terminating after copying parts of the string, or if you're writing past the allocated memory, you'll get those out-of-bounds garbage characters. Always double-check that every char array you use as a string ends with '\0'.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:19:25