字符串修改 [英] string modification
问题描述
大家好。我无法理解为什么以下程序无法正常工作。请解释。
int main()
{
char * t =" hello",* r;
r = t;
* r =''H'';
printf("%s",t);
返回0;
}
导致分段错误.Bye 。
问候,
Jerico
Hi all.I could not understand why the following program didn''t work.Please explain.
int main()
{
char *t="hello",*r;
r=t;
*r=''H'';
printf("%s",t);
return 0;
}
It results in segmentation fault.Bye.
Regards,
Jerico
推荐答案
大家好。我无法理解为什么下面的程序不起作用。请解释。
int main()
{
char * t =" hello",* r;
r = t;
* r =''H'';
printf("%s",t);
返回0;
}
导致分段错误.Bye 。
问候,
Jerico
Hi all.I could not understand why the following program didn''t work.Please explain.
int main()
{
char *t="hello",*r;
r=t;
*r=''H'';
printf("%s",t);
return 0;
}
It results in segmentation fault.Bye.
Regards,
Jerico
问题在于分配给你好"在程序数据段中,因此受到保护,任何修改它的尝试都会导致分段错误。您可以使用strdup函数来解决这个问题。这将在堆中创建一个可以自由修改的副本。
The problem is that the memory allocated for "hello" is in the programs data segment and is therefore protected and any attempt to modify it will result in a segmentation fault.. You can get around this by using the strdup function. This will create a duplicate in the heap that you can freely modify.
嗨jerico,
int main()
{
char * t =" hello",* r;
r = t;
* r =''H'';
printf("%s",t);
返回0 ;
}
我无法理解你的动机。如果你想重新分配一些字符串,那就无法更新常量数据了。
顺便说一下,来自哪里?
Hi jerico,
int main()
{
char *t="hello",*r;
r=t;
*r=''H'';
printf("%s",t);
return 0;
}
I could not understand ur motivation. If you wanted to reassign some string then its not possible to update a constant data.
By the way where r u from?
我看到了这样:
int main()
{
// char * t =" hello",* r ;
I see it in this way:
int main()
{
// char *t="hello",*r;
//" hello"被认为是const,所以它在数据段中并且不能被改变
char t [] =" hello",* r;
char t[]="hello",*r;
//" hello"被认为是数组,所以它在堆栈中(如果你更喜欢堆使用strdup)
r = t;
* r =''H'';
printf("%s",t);
返回0;
}
r=t;
*r=''H'';
printf("%s",t);
return 0;
}
这篇关于字符串修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!