【发布时间】:2020-05-11 16:58:57
【问题描述】:
我正在执行一个方法,用“%20”替换字符串中的所有空格。可以假设字符串末尾有足够的空间来容纳额外的字符,并且给定了字符串的“真实”长度。
示例:
输入:“约翰·史密斯先生”,13
输出:“Mr%20John%20Smith”
#include <stdio.h>
#include <string.h>
void URL(char str[], int length)
{
int spacecount = 0, index;
for (int i = 0; i < length; i++)
{
if (str[i] == ' ')
{
spacecount++;
}
}
index = length + spacecount * 2;
if (length < strlen(str))
str[length] = '\0';
for (int j = length - 1; j >= 0; j--)
{
if (str[j] == ' ')
{
str[index - 1] = '0';
str[index - 2] = '2';
str[index - 3] = '%';
index = index - 3;
}
else
{
str[index - 1] = str[j];
index--;
}
}
printf("%s", str);
}
int main()
{
char str[100];
int len;
printf("Enter the string : ");
scanf("%s", str);
printf("Enter the length : ");
scanf("%d", &len);
URL(str, len);
}
在使用 gcc 编译器执行上述代码时,我遇到了分段错误。我明白了,什么是分段错误。我想在这个程序中修复它。
【问题讨论】:
-
for (int j = length - 1; j >= 0; j++)这会永远存在,你不是说j--吗? -
我假设段错误发生在这里:
str[length] = '\0',你需要分配一个新的块:char newstr[index + 1],然后使用newstr而不是str -
我需要就地解决这个操作
-
你使用调试器并逐行执行吗?
-
没有机会就地替换空格,原始长度不够大,在java或pyhon之类的语言中你会得到
IndexOutOfBoundException(或类似的),C不控制它,但是它并不意味着你可以毫无后果地走出阵列
标签: c segmentation-fault