使用指针反转char字符串 [英] Reverse char string with pointers

查看:121
本文介绍了使用指针反转char字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要反向我的char字符串只有指针。我如何做到这一点?我的代码:

I need reverse my char string only with pointers. How can I do this? My code:

    // 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;



<但有时我看到一些额外的字符(看起来像临时符号)。我在哪里错过什么?谢谢!

Sometimes if works fine, I see only 5 chars, they are reversed. But sometimes I see some extra chars (looks like temp symbols). Where I miss something? Thank you!

推荐答案

阅读另一本书后,我完全理解指针以及如何正确分配内存。这里是我的最终代码,它正确地反转数组的字符串(我不需要通用代码,只是工作示例+没有std方法的逆转):

After reading another book I fully understand pointers and how to correctly allocate memory. Here is my final code which correctly reverse array of char string (I don't need universal code, just working example + without std methods for reversing):

// 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;

感谢所有帮助我的人!

这篇关于使用指针反转char字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆