修改 C 字符串常量? [英] Modifying C string constants?
问题描述
可能的重复:
为什么出现分段错误写入字符串?
我想编写一个函数来反转传递给它的给定字符串.但是我不能.如果我为 doReverse
函数(见下面的代码)提供一个字符数组,我的代码运行良好.
I want to write a function that reverses the given string passed into it.
But, I can not. If I supply the doReverse
function (see code below) with a character array, my code works well.
我不明白为什么这不起作用.我可以在 doReverse
中访问 str[0]
,但我无法使用字符指针更改数组的任何值.有什么想法吗?
I can't figure out why this does not work.
I am able to access str[0]
in doReverse
, but I can't change any value of the array by using a char pointer. Any ideas?
void doReverse(char *str) {
str[0] = 'b';
}
void main(void) {
char *str = "abc";
doReverse(str);
puts(str);
}
更新:
我知道如何通过向其传递字符数组来编写反向函数:
Update:
I know how to do write a reverse function by passing a character array to it:
void reverse1(char p[]) {
int i, temp, y;
for (i = 0, y = strlen(p); i < y; ++i, --y) {
temp = p[y-1];
p[y-1] = p[i];
p[i] = temp;
}
}
但是,我想编写另一个版本,将字符指针作为参数.
But, I want to write another version that gets a char pointer as a parameter.
推荐答案
最简单的解决方案是将str
的声明改为
The simplest solution is to change the declaration of str
to
char str[] = "abc";
这使 str
成为初始化为字符串abc"的字符数组.目前,您将 str
作为指向字符的指针,初始化为指向由字符串文字描述的字符串.有一个关键区别:字符串文字是只读的,以便编译器在存储它们的位置上具有最大的灵活性;修改它们是UB.但是 char 数组是可变的,因此可以修改它们.
This makes str
an array of char that is initialized to the string "abc". Currently you have str
as a pointer-to-char initialized to point to a string described by a string literal. There is a key difference: string literals are read-only to give the compiler maximum flexibility on where to store them; it is UB to modify them. But arrays of char are mutable, and so it's okay to modify those.
附注.main()
返回一个 int
.
这篇关于修改 C 字符串常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!