问题描述
大家好。我无法理解为什么以下程序无法正常工作。请解释。
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.
char t [] =" hello",* r;
char t[]="hello",*r;
r = t;
* r =''H'';
printf("%s",t);
返回0;
}
r=t;
*r=''H'';
printf("%s",t);
return 0;
}
这篇关于字符串修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!