Reputation: 23
I'm trying to reverse an array and simultaneously store it in a new array with for
loops. I have achieved it somewhat manually but not with loops. The first code below uses loops, the latter manually or literally.
char wrd[26],rev[26];
int y,i,s;
s=strlen(wrd)-1;
for(y=0;y<s;y++) for(i=s;i>=0;i--)
{
rev[y]=wrd[i];
}
Below is the same done manually; it works, but you get random chars used to fill the rest of the array:
{
char drw[26], wrd2[26];
int s,i=0;
s=strlen(wrd2)-1;
drw[0]=wrd2[s];
drw[1]=wrd2[s-1];
drw[2]=wrd2[s-2];
drw[3]=wrd2[s-3];
drw[4]=wrd2[s-4];
drw[5]=wrd2[s-5];
drw[6]=wrd2[s-6];
drw[7]=wrd2[s-7];
drw[8]=wrd2[s-8];
drw[9]=wrd2[s-9];
drw[10]=wrd2[s-10];
drw[11]=wrd2[s-11];
drw[12]=wrd2[s-12];
drw[13]=wrd2[s-13];
drw[14]=wrd2[s-14];
drw[15]=wrd2[s-15];
drw[16]=wrd2[s-16];
drw[17]=wrd2[s-17];
drw[18]=wrd2[s-18];
drw[19]=wrd2[s-19];
drw[20]=wrd2[s-20];
drw[21]=wrd2[s-21];
drw[22]=wrd2[s-22];
drw[23]=wrd2[s-23];
drw[24]=wrd2[s-24];
drw[25]=wrd2[s-25];
cout << drw;
}
Upvotes: 0
Views: 191
Reputation: 198294
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;
Upvotes: 3
Reputation: 3529
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.
Upvotes: 0