在编写一个从字符串中删除特定字符的简单函数时,我遇到了一个奇怪的问题:
While coding a simple function to remove a particular character from a string, I fell on this strange issue:
void str_remove_chars( char *str, char to_remove)
{
if(str && to_remove)
{
char *ptr = str;
char *cur = str;
while(*ptr != '')
{
if(*ptr != to_remove)
{
if(ptr != cur)
{
cur[0] = ptr[0];
}
cur++;
}
ptr++;
}
cur[0] = '';
}
}
int main()
{
setbuf(stdout, NULL);
{
char test[] = "string test"; // stack allocation?
printf("Test: %s
", test);
str_remove_chars(test, ' '); // works
printf("After: %s
",test);
}
{
char *test = "string test"; // non-writable?
printf("Test: %s
", test);
str_remove_chars(test, ' '); // crash!!
printf("After: %s
",test);
}
return 0;
}
我不明白为什么第二次测试失败了?在我看来,第一个符号 char *ptr = "string";
等同于这个:char ptr[] = "string";
.
What I don't get is why the second test fails?
To me it looks like the first notation char *ptr = "string";
is equivalent to this one: char ptr[] = "string";
.
不是这样吗?
两个声明不一样
char ptr[] = "string";
声明一个大小为 7
的 char 数组并用字符 s
对其进行初始化,t
,r
,i
,n
,g
和 .您被允许修改此数组的内容.
char ptr[] = "string";
declares a char array of size 7
and initializes it with the characters s
,t
,r
,i
,n
,g
and . You are allowed to modify the contents of this array.
char *ptr = "string";
将 ptr
声明为 char 指针,并使用 string literal " 的地址对其进行初始化string"
是只读的.修改字符串文字是一种未定义的行为.您所看到的(段错误)是未定义行为的一种表现.
char *ptr = "string";
declares ptr
as a char pointer and initializes it with address of string literal "string"
which is read-only. Modifying a string literal is an undefined behavior. What you saw(seg fault) is one manifestation of the undefined behavior.