出于一些奇怪的原因,当我将长度传递为12时,它会继续创建未启动的值,它会创建一个大约16的数组,并将剩下的数据存储在我不想要的垃圾中。任何人都知道为什么这不起作用?这是明天到期的作业,这是我的最后一个问题......任何帮助都将不胜感激。
char * convertToUppercase (char* toUpSize, int length) {
std::cout << "ToUpsize: " << toUpSize << "\nLength: " << length << "\n";
char * upsized = new char[length];
for (int i = 0; toUpSize[i]; i++) {
upsized[i] = toupper(toUpSize[i]);
}
return upsized;
}
答案 0 :(得分:4)
我认为您要么在for循环中写i< length
,而不是toUpSize[i]
:
for (int i = 0; i < length; i++) {
upsized[i] = toupper(toUpSize[i]);
}
如果要在toUpSize
循环条件中编写toUpSize[i]
,请将for
作为以空字符结尾的字符串传递。如果您这样做,那么在退出循环之后,您必须将\0
放在upsized
的末尾,索引为i
toUpSize[i]
\0
}}。为了实现这一点,您必须在i
循环之外移动for
的定义,以便在退出循环后可以使用它。
以空字符结尾的字符串是字符串末尾有\0
个字符的字符。
char x[] = {'N', 'a', 'w', 'a', 'z' };
char y[] = {'N', 'a', 'w', 'a', 'z', '\0' };
此处,x
不以空字符结尾的字符串,但y
是空字符串。
如果字符串定义为:
char z[] = "Nawaz";
const char *s = "Nawaz";
这里z
和s
是以空字符结尾的字符串,因为它们都是由“Nawaz”创建的,这是一个以空字符结尾的字符串。请注意,sizeof("Nawaz")
将返回6
,而不是5
,正是因为字符串末尾有\0
。
答案 1 :(得分:2)
如果要像字符串一样打印它,则需要对返回的数组进行空终止。确保它以null终止符结束。根据您计算length
参数的方式,您可能需要为数组添加额外的空间。您可能还希望确保传入的数组是以空值终止的。
答案 2 :(得分:0)
您需要添加终止字符:
char * convertToUppercase (char* toUpSize, int length) {
std::cout << "ToUpsize: " << toUpSize << "\nLength: " << length << "\n";
char * upsized = new char[length];
int i;
for (i = 0; toUpSize[i]; i++) { // stops when you get toUpSize[i]==0
upsized[i] = toupper(toUpSize[i]);
}
upsized[i] = '\0'; //add termination
return upsized;
}
您的代码假定length
是已分配数组的长度,而不是字符串的 length 。 strlen(toUpSize)
计算从toUpSize中的位置0开始不是'\ 0'的字符。
例如:strlen(“abc \ 0def”) - &gt; 3 sizeof(“abc \ 0def”) - &gt; 8!
答案 3 :(得分:0)
为什么你甚至打扰了char指针?这是C ++,而不是C。
#include <string>
#include <algorithm>
#include <cstring>
#include <iostream>
std::string to_upper_case(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(), toupper);
return str;
}
int main()
{
std::cout << to_upper_case("hello world\n");
}
如果您决定坚持使用C解决方案,请为NUL终结器再保留一个字符并将其放在那里:
char * upsized = new char[length + 1]; // note the +1
upsized[length] = 0;