Trying to reverse a C++ array and at the same time store it into a new array

限于喜欢 提交于 2019-12-02 07:56:04
Amadan

You have two nested loops, and they are not doing what you think they are doing. You only need one:

int y, s;

s = strlen(wrd) - 1;

for (y = 0; y<=s; y++)
{
    rev[y] = wrd[s - y];
}

and don't forget to terminate:

rev[s + 1] = 0;

Since you're using C++, take advantage of the libraries it offers. Depending on whether or not you want memory-sequential access to the elements (if you're going to read it out as a string, you probably do) you could use std::vector with reverse or alternatively a list/forward_list if contiguous access isn't an issue. std::list has the benefit of directly offering a reverse method.

#include <vector>
#include <algorithm>

using namespace std;

//int main() {
    vector<char> chars;
    const char *mystr = "abcdef";
    chars.reserve(6);
    chars.assign(mystr, mystr+6); //assuming we don't want the null terminator.
    reverse(chars.begin(), chars.end());
    cout << string(&chars.front(), chars.size()) << endl;
//}

The reserve is included to maximise the performance of the copy operation.

Additionally, if mystr was declared as a char array (or at least, pointed to writable memory) you could simply do reverse(mystr, mystr+6) too.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!