Copying an array into another array but in reverse

Jul 10, 2015 at 8:41pm
I have another program to write where i need to copy the contents of one array into a brand new array but in reverse order. I am suppose to use pointer dereferencing to do this but I think i found an easier way however i cannot get the array to display. My code will compile but it will just show an empty black box instead of displaying the contents of the array. So I have two questions. How would i go about doing this with with pointer dereferencing and why wont my code display the array. Thank you for any assistance!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 //This program makes a copy of an integer array and reverses it
//Written by 

#include <iostream> 
using namespace std; 
int main()
{
	const int SIZE = 10;
	int values[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int valuesReversed[10];
	int count;
	int lastNumArr1 = 9; 
	int firstNumArr2 = 0;
	while (firstNumArr2 < 9)
		valuesReversed[firstNumArr2] = values[lastNumArr1];
	lastNumArr1--;
	firstNumArr2++; 
	for (count = 0; count < 9; count++)
	{
		cout << "the reversed array is" << *(valuesReversed + count) << endl;
	}
}
Last edited on Jul 10, 2015 at 8:42pm
Jul 10, 2015 at 8:45pm
Your identation actually shows the mistake:
1
2
3
4
	while (firstNumArr2 < 9)
		valuesReversed[firstNumArr2] = values[lastNumArr1]; //Body of the loop
	lastNumArr1--; //Not body of loop. Executes after loop finishes.
	firstNumArr2++; //Which is never 
You are essentually assigning values[9] to valuesReversed[0] for infinite times (as indices do not change in loop body).
Use block statement to group those operations in loop body.
Jul 10, 2015 at 8:53pm
Thank you so much again! I should have caught that. I assumed the compiler would know what i meant. Do you know how i would allocate the reverse array with pointer dereferencing? Would i need to have the reverse array point at the last slot in the original array?
Jul 10, 2015 at 8:59pm
You can create two pointers, one pointing to the end of first array and second pointing to beginning of other. Then you would just run loop n times assigning and incrementing/decrementing pointers. Like that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int* pvalues = &values[SIZE - 1]; // or values + SIZE - 1
int* preverse = valuesReversed;
for(size_t i = 0; t < SIZE; ++t) {
    *preverse = *pvalues;
    ++preverse;
    --pvalues;
}

//Condensed example:
for(size_t i = 0; t < SIZE; ++t) 
    *preverse++ = *pvalues--;

//Another approach:
while(preverse < valuesReversed + SIZE)
    *preverse++ = *pvalues--;
Jul 10, 2015 at 9:09pm
I see that makes sense. I appreciate you helping me with all this! You have literally made learning programming fun and enjoyable for me again!
Topic archived. No new replies allowed.