如何使用指针更改字符串中的字符? [英] How to change a character in a string using pointers?

查看:598
本文介绍了如何使用指针更改字符串中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此代码有疑问

int main() {
     char *My_St = "abcdef";
     *(My_St+1)='+';
     printf("%s\n",My_St);
     return 0;
}

我构建了这段代码,没有错误,但是当我尝试运行它时,它抛出了分段错误,有人可以告诉我什么地方出问题了

i built this code and has no errors, but when i try to run it, it throws a segmentation fault, could someone tell what's wrong

推荐答案

不能,因为试图修改const数据.

You can't because you are trying to modify const data.

将其更改为:

char My_St[] = "abcdef";

然后您将能够对其进行更改.

Then you will be able to change it.

想想您在做什么,您在声明指向"abcdef"的指针.它是一个指针,不是字符数组.我的意思是"abcdef"生活在服务器场的.text区域中,而这是不可变的.

Think about what you were doing, you were declaring a pointer that pointed to "abcdef". It IS a pointer, not an array of chars. "abcdef" lives in the farm, I mean, in the .text area of your program and that is immutable.

当按照我已说明的方式进行操作时,您正在告诉编译器:我声明此数组,该数组将具有容纳"abcdef"所需的所有字符,并在您存在的地方复制"abcdef".

When you do it the way I've shown, you are telling the compiler: i'm declaring this array, that will have as many chars as are needed to accommodate "abcdef" and also, as you are there, copy "abcdef" to it.

这篇关于如何使用指针更改字符串中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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