修改C字符串常量? [英] Modifying C string constants?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string\">Why做写入字符串时,我得到一个分段错误?
块引用>我想写反转传递给它给定的字符串的函数。
但是我不能。如果我提供doReverse
功能(见$ C $下面c)与一个字符数组,我的code效果很好。我想不通为什么这是行不通的。
我能够访问海峡[0]
在doReverse
,但我无法改变的数组的任何值使用字符指针。任何想法?无效doReverse(字符* STR){
海峡[0] ='B';
}无效的主要(无效){
char *之海峡=ABC;
doReverse(STR);
看跌期权(STR);
}更新:
我知道该怎么做传递一个字符数组来写一个反转功能:
无效reverse1(字符P []){
INT I,温度,Y; 对于(I = 0,Y = strlen的(P); I&所述; Y; ++ i的,--y){
TEMP = P [Y-1];
P [Y-1] = P [I];
P [i] =温度;
}
}不过,我想要写另一个版本,获取一个字符指针作为参数。</ P>
解决方案最简单的解决方法是
STR
的声明更改为字符海峡[] =ABC;
这使得
STR
字符数组的初始化字符串ABC。目前,你有STR
作为初始化为指向一个字符串描述一个字符串指针到字符。有一个关键的区别:字符串文字是只读的给编译器在哪里来存储它们最大的灵活性;它是UB修改它们。但字符数组是可变的,所以它的好修改这些。PS。
的main()
返回INT
。Possible Duplicate:
Why do I get a segmentation fault when writing to a string?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.I can't figure out why this does not work. I am able to access
str[0]
indoReverse
, 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.
解决方案The simplest solution is to change the declaration of
str
tochar str[] = "abc";
This makes
str
an array of char that is initialized to the string "abc". Currently you havestr
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.PS.
main()
returns anint
.这篇关于修改C字符串常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!