带指针的反向char字符串
我只需要用指针反转我的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个字符,它们是相反的。但有时我会看到一些额外的字符(看起来像是临时符号)。我错过了什么?谢谢!
读另一本书我完全理解指针和如何正确地分配内存后。这是我最后的代码,正确扭转字符的字符串数组(我不需要通用代码,只是工作示例+无性病的方法逆转):
// not edited part - based on exercise (I mean I cannot change pS to char[5] etc.
char s[10] = "abcde";
char *pS;
pS = new char[strlen(s) + 1]; // allocate correct memory size based on string size
cout << "Size is " << sizeof(pS) << endl; // just for testing
int count = strlen(s); // for iteration
pS[count] = '\0'; // last symbol must be '\o' (thanks to Mr.Yellow)
for (int i = 0; i < 10; i++) // 10 because array of char still has 10 elements
{
if (s[i] != '\0') // looks like "not garbage memory"
{
count--;
pS[count] = s[i]; // set correct value
}
}
cout << "Reversed = " << pS << endl;
谢谢所有谁帮助我!
只是给你的提示如何使用指针扭转字符串:
- 取两个指针前,其中前指向字符串后的第一个字符后指向字符串的最后一个字符。
- 检查前部是否小于后部
- 如果是,则交换第一个和最后一个字符的值。如果不是,只需打印字符串。
- 递增前指针和递减后指针
- 重复从步骤2
您的字符数组的“s”包含10个字符,但只用“ABCDE”并初始化数组的第一个6个字符\ 0终止符。 当您遍历整个数组时,您将访问未初始化的字符。
我还看到,你试图写入内存,你没有分配。 您只为您的“pS”指针分配1个字符的内存,但您尝试访问它的内存,就像它是for循环中的一组字符一样。
,而不是使用硬编码:
int count = 5;
,你也可以使用字符串函数的strlen()来确定C-字符串的长度。
编辑(未经测试的代码):
char s[10] = "abcde";
char pS[10];
for (int i = 0; i < strlen(s); i++)
{
if (s[i] == '\0') // not null
{
// stop loop, as soon as you reach the end of the original string
break;
}
pS[strlen(s) - 1 - i];
}
// now add the termination char \0 to your pS array
pS[strlen(s)] = '\0';
cout << "Reversed = " << pS;
谢谢你的穿着。我如何为5个字符分配内存? –
@VladyslaveSemenchenko _“如何为5个字符分配内存?”_像这样'pS = new char [5];'不要忘记调用delete [] pS;',如果它不再被使用。 –
转到:嗯......仍然看到额外的符号。所以我的Ts字符串看起来像edcba,然后是一些临时符号。看起来我错了分配内存:( –
你不应该使用硬编码的数字。使用strlen来查找长度。 – CreativeMind
'pS = new char;'为_single_'char'分配空间,而不是数组。 –
你是否应该创建一个新的字符串或原来的位置?目前还不清楚“这是不能修改”的意思。 – molbdnilo