C语言大写 [英] Uppercase in C language

查看:27
本文介绍了C语言大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

void changeToCapital(char* str)
{
    int i;
    for (i=0; i<strlen(str); i++) 
    {
        str[i] =str[i] -32;
    }
}

并且这个方法应该得到一个 char* 变量,并将其更改为大写.出于某种原因,我收到一条错误消息,提示 EXECUTE_BAD_ACCESS.

and this method is supposed to get a char* variable, and change it to its uppercase. For some reason I'm getting an error saying EXECUTE_BAD_ACCESS.

调用函数:

char* s = "itzik";
changeToCapital(s);
printf("%s\n",s);

我在这里做错了什么?

推荐答案

这很可能是因为您向它传递了一个指向不可写内存的指针,例如从字符串文字中获得的指针:

This is most likely because you are passing it a pointer to non-writable memory, such as one obtained from a string literal:

char *ptr = "Hello";
changeToCapital(ptr); // <<== ERROR !

您可以更改调用以避免错误:

You can change the call to avoid the error:

char ptr[] = "Hello";
changeToCapital(ptr);

顺便说一句,只有当所有字母都为小写时,您对大写的更改才有效.您应该使用 toupper(ch) 函数而不是减去 32.

On a side note, your change to upper case works only when all letters are in the lower case. You should use toupper(ch) function instead of subtracting 32.

void changeToCapital(char* str) {
    for (; *str = toupper(*str) ; str++)
        ;
}

这篇关于C语言大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆