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

C语言字符数组问题:查找目标字符首次索引却返回-256

问题分析与解决方案

你的程序返回-256的核心原因是读取单个字符时用错了scanf格式符:

  • argumento是单个char变量,但你用了%s格式符读取。%s会读取输入的字符串(包括末尾的终止符\0),而单个char只有1字节存储空间,写入时会发生缓冲区溢出,直接覆盖相邻变量res的内存,导致res的初始值-1被破坏成-256。

修正步骤:

  1. 把读取单个字符的scanf("%s", &argumento);改成scanf(" %c", &argumento);——这里的空格是为了跳过输入前的空白字符(比如之前输入操作留下的换行符),避免读取到无效字符。
  2. (可选)如果需要读取包含空格的完整字符串,把读取linea的scanf("%s", linea);改成fgets(linea, DIM, stdin);,同时记得用strcspn去掉fgets自动读取到的末尾换行符。

修正后的完整代码:

#include <stdio.h>

#define DIM 80

int main() {
    char argumento;
    char linea[DIM];
    int res = -1;
    printf("Ponga el caracter argumento\n");
    scanf(" %c", &argumento);
    printf("ponga la cadena:\n");
    scanf("%s", linea);

    int i = 0;

    while (linea[i] != '\0' && res == -1) {
        if (linea[i] == argumento) {
            res = i;
        }
        ++i;
    }

    printf("El primer caracter que coincide es de indice: %d\n", res);
    return 0;
}

测试时注意:输入单个字符后按回车,再输入目标字符串,程序就能正确返回匹配的索引。比如输入字符a、字符串abcde会返回索引0;若输入字符不在字符串中,返回初始值-1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:10:32