通过添加值更改字符串中的字符会导致运行时错误
Changing characters in a string by adding value causes runtime error
我正在尝试编写一个代码来更改字符数组中的字母。
大部分代码运行良好。但是,当我尝试将大写字母更改为小写字母(反之亦然)时,代码不起作用并且程序结束。
我推测是因为指针不能使用自身或者类似的原因。但是我说不出正确的理由。
如果是xy问题我很担心,但请理解我不想上传整个问题,因为这是我的作业,我想尽可能自己解决问题,我认为这是学习程序的正确方法。
#include <stdio.h>
#include <string.h>
int main(void){
//initialize
char *ae = "sample";
// for (){}
ae[0] -= 36;//at this point, program stops
// tried ae[0] = ae[0] -36 ; *ae = *ae - 36; and so on...
printf("%c", ae[0] - 36);
}
感谢您的宝贵时间:)
这个表达式...
char *ae = "sample";
...用 string literal, these are read-only and can't be modified. The expression ae[0] -= 36;
attempts to change the first character of this string literal, but this is not allowed and causes undefined behavior.
初始化指针
改为使用:
char ae[] = "sample";
在另一个注释中,从字母字符中减去 36
不会将其转换为大写,至少在 ASCII 编码中不会,您可能意味着 32
.
无论如何,这不是很便携,您可以使用 <ctype.h>
库中的 toupper()
and tolower()
以获得更强大的选项。
我正在尝试编写一个代码来更改字符数组中的字母。
大部分代码运行良好。但是,当我尝试将大写字母更改为小写字母(反之亦然)时,代码不起作用并且程序结束。
我推测是因为指针不能使用自身或者类似的原因。但是我说不出正确的理由。
如果是xy问题我很担心,但请理解我不想上传整个问题,因为这是我的作业,我想尽可能自己解决问题,我认为这是学习程序的正确方法。
#include <stdio.h>
#include <string.h>
int main(void){
//initialize
char *ae = "sample";
// for (){}
ae[0] -= 36;//at this point, program stops
// tried ae[0] = ae[0] -36 ; *ae = *ae - 36; and so on...
printf("%c", ae[0] - 36);
}
感谢您的宝贵时间:)
这个表达式...
char *ae = "sample";
...用 string literal, these are read-only and can't be modified. The expression ae[0] -= 36;
attempts to change the first character of this string literal, but this is not allowed and causes undefined behavior.
改为使用:
char ae[] = "sample";
在另一个注释中,从字母字符中减去 36
不会将其转换为大写,至少在 ASCII 编码中不会,您可能意味着 32
.
无论如何,这不是很便携,您可以使用 <ctype.h>
库中的 toupper()
and tolower()
以获得更强大的选项。