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

C语言中使用toupper()生成新大写字符串报错求助

问题分析与修复

错误原因

  • 空数组无法操作:char new_word[] = {};定义了长度为0的字符数组,既没有存储空间,且C语言中数组名是不可修改的常量指针,不能用=直接赋值,这就是报错的直接原因。
  • 字符串操作逻辑错误:new_word = new_word + toupper(word[i]);不符合C语言字符串操作规则,C语言不能通过算术运算符直接拼接字符串,必须逐个字符写入内存空间。

修复方案

1. 分配足够内存

目标字符串长度与原字符串一致,还需额外1个字节存储字符串结束符\0,可根据原字符串长度初始化数组:

int len = strlen(word);
char new_word[len + 1]; // +1 用于存放字符串结束符 '\0'

2. 逐个转换写入字符

循环遍历原字符串,将小写字符转大写后写入new_word对应位置,最后手动添加字符串结束符。

完整修正代码

#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main (void)
{
    string word = "science";
    int len = strlen(word);
    char new_word[len + 1]; // 分配包含结束符的足够空间

    for (int i = 0; i < len; i++)
    {
        // 直接转换字符,toupper兼容非小写字符(此处已通过islower判断)
        new_word[i] = toupper(word[i]);
    }
    new_word[len] = '\0'; // 必须添加结束符,否则会出现乱码

    printf("原字符串:%s\n转换后:%s\n", word, new_word);
    return 0;
}

额外说明

  • 若原字符串是动态输入(比如用get_string()),上述写法依然适用,strlen可正确获取输入字符串长度。
  • 为避免字符为负数时的未定义行为,可将toupper的参数转为unsigned char类型:
    new_word[i] = toupper((unsigned char)word[i]);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:05:32