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

C语言使用switch()时报subscripted value相关错误原因求解

报错原因说明

该报错和switch语法本身没有任何关系,是[]下标操作的合法性校验触发的报错,错误点完全和switch无关:

  • 你在main函数中定义的inputString是char类型的单字符变量,既不是数组也不是指针,根本不支持inputString[0]这种下标取值写法,也无法匹配readLine函数第一个参数要求的char[]类型
  • 额外你写的readLine函数还存在未初始化问题:局部变量i没有赋初值就执行i++,c没有初始化就进入while(c!='\n')判断,两个操作都会触发未定义行为
  • 还存在输入越界风险:readLine没有判断输入长度是否超过数组上限,可能触发缓冲区溢出
修复后的完整代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 30
void printArray(char a[], int length){
    int i;
    printf("[");
    for (i=0; i<length; i++){
        if (i!= length-1){
            if (a[i]=='\0'){
                printf("\\0,");
            }
            else if (a[i]=='\n'){
                printf("\\n,");
            }
            else{
                printf("%c,",a[i]);
            }
        }
        else if (i == length-1){
            if (a[i]=='\0'){
                printf("\\0");
            }
            else if (a[i]=='\n'){
                printf("\\n");
            }
            else{
                printf("%c",a[i]);
            }
        }
    }
    printf("]\n");
}

void printString(char str[]){
    int length = strlen(str),i;
    putchar('\"');
    for (i=0;i<length;i++){
        putchar(str[i]);
    }
    putchar('\"');
}

void readLine(char str[], int length){
    int i = 0;
    char c;
    // 先读取再判断,同时加长度校验避免越界
    while((c=getchar())!='\n' && i < length -1){
        str[i]=c;
        i++;
    }
    str[i]='\0';
}
int main()
{
    char string1[12] = "hello", string2[12] = "hello\n", string3[12] = "hello\n\0you\n", string4[12] = "0123456789AB";
    char inputString[LENGTH]; // 修改为字符数组类型
    do{
        printf("Command [qpasoirR123]? ");
        readLine(inputString, LENGTH);
        switch (inputString[0]){
        case 'q':
            printf("Bye!\n");
            break;
        default:
            printf("Unknown command '%c'\n", inputString[0]);
            break;
        }
    } while (inputString[0]!='q');
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:39:00