题目描述
使用“%20”替换一个字符创中的空格
相关代码
我的代码是这样子的
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "malloc.h"
#define PLACESPACE "%20"
int main(void)
{
char *replaceSpace(const char *str, int length);
char *str = "This is test string!";
char *newStr = NULL;
newStr = replaceSpace(str, sizeof(str)); // 长度有EOF
printf("%s\n", newStr);
free(newStr);
return 0;
}
char *replaceSpace(const char *str, int length)
{
int spaceCount = 0; //空格总数
// 记录空格
while (*str != EOF)
{
// 遍历字符串字符
if (*(str++) == ' ')
{
// 选择指针的位置再这里偏移
spaceCount++;
}
}
// 替换空格
char *newStr = (char *)malloc(length + spaceCount*3); // 新字符串的存储位置
newStr[0] = EOF;
for (int i = 0; i < sizeof(newStr); i++)
{
// 循环,如果遇到空格便替换
if (*str == ' ')
{
strcat(newStr, PLACESPACE);
str++;
i += 3;
continue;
}
newStr[i] = *str;
newStr[i + 1] = EOF;
str++;
}
return newStr;
}
问题描述
VS就像是真样子报错
gdb的描述是这样子的
我不知道发生了什么,求解
include "malloc.h" 改为 #include <malloc.h>