char *str=“STRING"之间的区别和 char str[] = “字符串"? [英] Difference between char *str="STRING" and char str[] = "STRING"?
本文介绍了char *str=“STRING"之间的区别和 char str[] = “字符串"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在编写一个从字符串中删除特定字符的简单函数时,我遇到了一个奇怪的问题:
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
和