Reputation: 85
I'm trying to reverse each row of a two dimensional array and store that in a new two dimensional array. I understand I need to use a temp pointer, but I seem to be a bit lost on how to actually do this all. I've tried researching the problem but couldn't find anything specific to mine.
using namespace std;
void compute(int *p1, int *p2, int ROWS, int COLUMNS);
int main() {
const int COLUMNS = 3;
const int ROWS = 3;
int A[ROWS][COLUMNS] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int B[ROWS][COLUMNS] ;
int *p1, *p2;
p1 = &A[0][0];
p2 = &B[0][0];
compute(p1, p2, ROWS, COLUMNS);
return 0;
}
void compute(int *p1, int *p2, int ROWS, int COLUMNS) {
int *savePtrA, *savePtrB, *temp;
savePtrA = p1;
savePtrB = p2;
temp = p1+COLUMNS;
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLUMNS; j++) {
temp = *p1;
*p2 = *p1 + 1;
p1--;
p2++;
}
}
for (int i = 0; i < ROWS; ++i) {
for (int j = 0; j < COLUMNS; ++j) {
cout << setw(5) << *savePtrA;
savePtrA++;
}
cout << setw(10) << " ";
for (int k = 0; k < COLUMNS; ++k) {
cout << setw(5) << *savePtrB;
savePtrB++;
}
cout << setw(10) << " ";
cout << endl;
}
}
Upvotes: 0
Views: 2692
Reputation: 180
I do not know if it is what you are looking for but change your code so that it does what you ask, although it can be done in an easier way
#include <iostream>
#include <iomanip>
using namespace std;
void compute(int *p1, int *p2, int COLUMNS);
int main() {
const int COLUMNS = 3;
const int ROWS = 3;
int A[ROWS][COLUMNS] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int B[ROWS][COLUMNS] ;
int *p1, *p2, *savePtrA, *savePtrB;
savePtrA = p1;
savePtrB = p2;
for (int i = 0; i < ROWS; ++i) {
p1 = &A[i][0];
p2 = &B[i][0];
compute(p1, p2, COLUMNS);
}
for (int i = 0; i < ROWS; ++i) {
savePtrA = &A[i][0];;
savePtrB = &B[i][0];
for (int j = 0; j < COLUMNS; ++j) {
cout << setw(5) << *savePtrA;
savePtrA++;
}
cout << setw(10) << " ";
for (int k = 0; k < COLUMNS; ++k) {
cout << setw(5) << *savePtrB;
savePtrB++;
}
cout << setw(10) << " ";
cout << endl;
}
return 0;
}
void compute(int *p1, int *p2, int COLUMNS) {
for (int j = COLUMNS-1; j >= 0; j--) {
*p2 = *(p1 + j);
p2++;
}
}
Upvotes: 1
Reputation: 35455
You could simply call std::reverse_copy in a loop:
#include <algorithm>
int main()
{
const int COLUMNS = 3;
const int ROWS = 3;
int A[ROWS][COLUMNS] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int B[ROWS][COLUMNS] ;
for (int i = 0; i < ROWS; ++i)
std::reverse_copy(&A[i][0], &A[i][COLUMNS], &B[i][0]);
}
The source array is given in the first two arguments -- a pointer to the first element in the source row, and a pointer to one past the last element in the source row. The third parameter is the destination row, and that is merely a pointer to the first element in the B
row.
Upvotes: 2