我只需要用指针反转我的char字符串。我怎样才能做到这一点?我的代码:带指针的反向char字符串
// this cannot be modified !!!
char s[10] = "abcde";
char *pS;
// my code
pS = new char;
int count = 5;
for (int i = 0; i < 10; i++)
{
if (s[i] != '\0') // not null
{
pS[count - 1] = s[i];
count--;
}
}
cout << "Reversed = " << pS;
有时候,如果工作得很好,我看到的只有5个字符,它们是相反的。但有时我会看到一些额外的字符(看起来像是临时符号)。我错过了什么?谢谢!
你不应该使用硬编码的数字。使用strlen来查找长度。 – CreativeMind
'pS = new char;'为_single_'char'分配空间,而不是数组。 –
你是否应该创建一个新的字符串或原来的位置?目前还不清楚“这是不能修改”的意思。 – molbdnilo