本文介绍了产生不带指针的大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个大写的函数,该函数将字符串中的所有小写字符转换为它们的大写等效项.

I am trying to write a function, uppercase, that converts all lowercase characters in a string into their uppercase equivalents.

但是,我的代码中出现了Bus 10错误.我知道不能在C中修改字符串文字;因此,我不确定这是否是正确的方法.

However, I am getting a Bus 10 error in my code. I know that string literals cannot be modified in C; so, I am not sure if this is the right approach.

我的代码如下:

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

int uppercase(char source[])
{
 int i;

 for(i=0; i<=strlen(source); ++i)
    if (source[i]>= 'a' && source[i]<= 'z')
        source[i]= source[i]-'a' +'A';
    else
        source[i]=source[i];
}

int main(){
    uppercase("cold");

    return 0;
}

理想情况下,此函数应返回COLD.我想错误在于我的整个if语句.

Ideally this function should return COLD.I suppose the error lies in my whole if statement.

推荐答案

崩溃的原因是您的代码修改了字符串文字.字符串文字中的字符放置在受保护的内存区域中,因此不能更改:这是未定义的行为.

The reason you get a crash is that your code modifies a string literal. Characters inside string literals are placed in protected memory area, and therefore may not be changed: it us undefined behavior.

替换此

uppercase("cold");

与此:

char cold[] = "cold";
uppercase(cold);

现在,字符串的字符被放置在内存的可修改区域中,可让您根据需要进行更改.

Now the characters of the string are placed in a modifiable area of memory, allowing you to make changes as needed.

这篇关于产生不带指针的大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 17:13