我有下面的代码将从字符串中删除尾随空格但我不知道 进入这段代码,因为它给出了分段错误问题??
void main(void);
char* rtrim(char*);
void main(void)
{
char* trail_str = "This string has trailing spaces in it. ";
printf("Before calling rtrim(), trail_str is '%s'\n", trail_str);
printf("and has a length of %d.\n", strlen(trail_str));
rtrim(trail_str);
printf("After calling rtrim(), trail_str is '%s'\n", trail_str);
printf("and has a length of %d.\n", strlen(trail_str));
}
char* rtrim(char* str)
{
int n = strlen(str) - 1;
while (n>0)
{
if (*(str+n) != ' ')
{
*(str+n+1) = '\0';
break;
}
else
n--;
}
return str;
}
答案 0 :(得分:3)
trail_str指向内存中的常量区域,因此无法在*(str+n+1) = '\0'
char* trail_str = "This string has trailing spaces in it. ";
你实际生成一个常量字符串:"This string has trailing spaces in it. "
并告诉trail_str
指向它。
答案 1 :(得分:2)
char* trail_str = "This string has trailing spaces in it. ";
tail_str
指向的字符串可以存储在只读内存中。你不能修改它。
如果要修改它,则需要为其分配存储空间并将该字符串复制为常量。
(另外,main
应该返回int
,而不是void
。)