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!
//This program makes a copy of an integer array and reverses it
//Written by
#include <iostream>
usingnamespace std;
int main()
{
constint 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;
}
}
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.
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?
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: