当传入参数伟nullptr时为什么会引发异常?
这是一个空格替换的问题#include<iostream>
using namespace std;
void ReplaceBlank(char str[], int length)
{
if (str == nullptr && length <= 0)
return;
/*originalLength 为字符串str的实际长度*/
int originalLength = 0;
int numberOfBlank = 0;
int i = 0;
while (str != '\0')
{
++originalLength;
if (str == ' ')
++numberOfBlank;
++i;
}
/*newLength 为把空格替换成'%20'之后的长度*/
int newLength = originalLength + numberOfBlank * 2;
if (newLength > length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
{
if (str == ' ')
{
str = '0';
str = '2';
str = '%';
}
else
{
str = str;
}
--indexOfOriginal;
}
}
void replaceblank(char str[], int length)
{
cout << str << endl;
if (str == nullptr && length <= 0)
return;
int originalLength = 0;
int numOfBlank = 0;
int i = 0;
while (str != '\0')
{
originalLength++;
if (str == ' ')
numOfBlank++;
i++;
}
int newLength = originalLength + numOfBlank * 2;
if (newLength > length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0&&indexOfNew>indexOfOriginal)
{
if (str == ' ')
{
str = '0';
str = '2';
str = '%';
}
else
{
str = str;
}
--indexOfOriginal;
}
cout << str << endl;
}
void main()
{
char str[] = "i o v";
replaceblank(nullptr, 0);
//ReplaceBlank(nullptr, 0);
system("pause");
} 不懂为啥发帖的时候不允许我用代码格式提交故在评论区再次附上代码
#include<iostream>
using namespace std;
void ReplaceBlank(char str[], int length)
{
if (str == nullptr && length <= 0)
return;
/*originalLength 为字符串str的实际长度*/
int originalLength = 0;
int numberOfBlank = 0;
int i = 0;
while (str != '\0')
{
++originalLength;
if (str == ' ')
++numberOfBlank;
++i;
}
/*newLength 为把空格替换成'%20'之后的长度*/
int newLength = originalLength + numberOfBlank * 2;
if (newLength > length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
{
if (str == ' ')
{
str = '0';
str = '2';
str = '%';
}
else
{
str = str;
}
--indexOfOriginal;
}
}
void replaceblank(char str[], int length)
{
cout << str << endl;
if (str == nullptr && length <= 0)
return;
int originalLength = 0;
int numOfBlank = 0;
int i = 0;
while (str != '\0')
{
originalLength++;
if (str == ' ')
numOfBlank++;
i++;
}
int newLength = originalLength + numOfBlank * 2;
if (newLength > length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0&&indexOfNew>indexOfOriginal)
{
if (str == ' ')
{
str = '0';
str = '2';
str = '%';
}
else
{
str = str;
}
--indexOfOriginal;
}
cout << str << endl;
}
void main()
{
char str[] = "i o v";
replaceblank(nullptr, 0);
//ReplaceBlank(nullptr, 0);
system("pause");
} ;传入nullptr,先输出肯定异常啊
cout << str << endl;
if (str == nullptr && length <= 0)
return;
要把判断写在最前面
if (str == nullptr && length <= 0)
return;
cout << str << endl; xieglt 发表于 2020-8-31 09:18
;传入nullptr,先输出肯定异常啊
cout
阿阿阿我知道了谢谢 我都没注意到 我多加了一个输出str{:10_266:}
页:
[1]