字符*海峡=&QUOT之间的差异; STRING"和char海峡[] =" STRING"? [英] Difference between char *str="STRING" and char str[] = "STRING"?
问题描述
虽然编码一个简单的函数从一个字符串中删除特定字符,我倒在这个奇怪的问题:
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 != '\0')
{
if(*ptr != to_remove)
{
if(ptr != cur)
{
cur[0] = ptr[0];
}
cur++;
}
ptr++;
}
cur[0] = '\0';
}
}
int main()
{
setbuf(stdout, NULL);
{
char test[] = "string test"; // stack allocation?
printf("Test: %s\n", test);
str_remove_chars(test, ' '); // works
printf("After: %s\n",test);
}
{
char *test = "string test"; // non-writable?
printf("Test: %s\n", test);
str_remove_chars(test, ' '); // crash!!
printf("After: %s\n",test);
}
return 0;
}
我不明白为什么是第二次测试失败?
对我来说,它看起来像第一表示的char * PTR =串;
等同于这一个:字符PTR [] =字符串;
。
是不是这样的?
推荐答案
这两个声明是不一样的。
The two declarations are not the same.
字符PTR [] =串;
声明大小的字符数组 7
并用它初始化字符结果取值
, T
,研究
, I
, N
,先按g
和 \\ 0
。您的允许以修改该数组的内容。
char ptr[] = "string";
declares a char array of size 7
and initializes it with the characters
s
,t
,r
,i
,n
,g
and \0
. You are allowed to modify the contents of this array.
的char * PTR =串;
声明 PTR
作为一个字符指针和地址初始化它字符串的串
是只读的。修改字符串是一个未定义行为即可。你所看到的(赛格故障)是不确定的行为的一种表现。
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.
这篇关于字符*海峡=&QUOT之间的差异; STRING"和char海峡[] =" STRING"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!