替换字符串 C 的单个字符元素
我正在尝试在 C 上做一些非常基本的事情,但我不断遇到分段错误。我想做的就是用不同的字母替换一个单词的字母 - 在这个例子中用 L 替换 l。任何人都可以帮助解释我哪里出了问题吗?我认为这应该是一个非常基本的问题,我只是不知道为什么它不起作用。
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
char *string1;
string1 = "hello";
printf("string1 %s\n", string1);
printf("string1[2] %c\n", string1[2]);
string1[2] = 'L';
printf("string1 %s\n", string1);
return 0;
}
对于我的输出我得到
字符串1你好
字符串1[2] l
分段错误
谢谢!
I am trying to do something really basic on C but I keep getting a segmentation fault. All I want to do is replace a letter of a word with a different letter- in this example replace the l with a L. Can anyone help explain where I have gone wrong? It should be a really basic problem I think, I just have no idea why its not working.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
char *string1;
string1 = "hello";
printf("string1 %s\n", string1);
printf("string1[2] %c\n", string1[2]);
string1[2] = 'L';
printf("string1 %s\n", string1);
return 0;
}
For my output I get
string1 hello
string1[2] l
Segmentation fault
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法更改字符串文字,这是未定义的行为。试试这个:
或者也许:
You can't change string literals, it's undefined behavior. Try this:
Or maybe:
string1
指向字符串文字,并且字符串文字是不可修改的。您可以做的是使用字符串文字的元素初始化数组。
string1
数组的元素是可以修改的。string1
points to a string literal and string literals are non-modifiable.What you can do is initialize an array with the elements of a string literal.
the elements of
string1
array are modifiable.运行代码时,字符串文字将位于只读部分中。操作系统不允许代码更改该内存块,因此您会遇到段错误。
当您运行代码时,字符串文字将被推入堆栈。
When running the code, the string literal will be in a section that is read-only. OS does not allow the code to change that block of memory, so you get a seg-fault.
The string literal will be pushed onto the stack when you run the code.
您正在尝试更改字符串文字,这在 C 中是未定义的行为。
而是使用
string1[]="hello";
您遇到的分段错误是因为文字可能存储在内存的只读部分中,并且尝试写入它会产生未定义的行为。
you are trying to change a string literal which is undefined behavior in C.
Instead use
string1[]="hello";
Segmentation fault you get is because the literal is probably stored in the the read only section of the memory and trying to write to it produces undefined behavior.