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

C语言实现读取数组L1、L2输出L1-L2功能运行异常求助

问题原因及修复方案

你的代码核心问题出在子数组匹配的逻辑设计上,额外引入的temp变量虽然在少数场景下能正常工作,但逻辑不严谨,遇到部分匹配场景容易出现索引偏移错误,此外还有多处边界判断缺失、类型定义不合理的问题。

具体问题点

  • 缺少前置边界判断:如果L2长度大于L1,或者L2长度为0,不可能是L1的子数组,直接返回结果即可,不需要走匹配逻辑
  • 字符数组定义为int类型语义错误,应该用char类型存储字符
  • 匹配逻辑依赖temp变量记录起始位置,没有覆盖所有匹配场景,容易出现索引错误
  • 输出结果时末尾会多带一个空格,和预期格式不符

修复后的代码

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

int main() {
    int n1, n2, j = 0, i = 0, match_start = 0, found = 0;

    // 数组输入
    printf("Enter number of characters in L1: ");
    scanf("%d", &n1);
    char l1[n1];
    for (int i = 0; i < n1; i++) {
        printf("Enter character %d: ", i + 1); 
        scanf(" %c", &l1[i]);
    }
    printf("Enter number of characters in L2: ");
    scanf("%d", &n2);
    char l2[n2];
    for (int i = 0; i < n2; i++) {
        printf("Enter character %d: ",i + 1); 
        scanf(" %c", &l2[i]);
    }

    // 前置边界判断
    if (n2 > n1 || n2 <= 0) {
        printf("l2 is not a sub array of l1");
        exit(0);
    }
    
    // 子数组匹配(标准暴力匹配逻辑)
    while (i <= n1 - n2) {
        match_start = i;
        j = 0;
        while (j < n2 && l1[i + j] == l2[j]) {
            j++;
        }
        if (j == n2) {
            found = 1;
            break;
        }
        i++;
    }
    
    if (found == 0) {
        printf("l2 is not a sub array of l1");
    } else {
        printf("{");
        int first = 1;
        for (int i = 0; i < n1; i++) {
            if (i >= match_start && i < (match_start + n2)) 
                continue;
            if (!first) {
                printf(" ");
            }
            printf("%c", l1[i]);
            first = 0;
        }
        printf("}");
    }

    exit(0);
}

修复说明

  • 新增了前置边界判断,避免无效匹配逻辑
  • 替换为标准暴力匹配逻辑,不需要额外的索引回退变量,match_start直接记录每次匹配的起始位置,找到匹配后直接使用,逻辑清晰不易出错
  • 字符数组改为char类型,语义准确
  • 优化了输出逻辑,避免末尾多余空格,符合示例输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:06:03