IN C using namespace std int reverseint list int size for i
IN C++:
using namespace std;
int* reverse(int* list, int size)
{
for (int i = 0, j = size - 1; i < j; i++, j--)
{
// Swap list[i] with list[j]
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
return list;
}
void printArray(int* const list, int size)
{
for (int i = 0; i < size; i++)
cout << list[i] << \" \";
}
int main()
{
int list[] = {1, 2, 3, 4, 5, 6};
int* p = reverse(list, 6);
printArray(p, 6);
return 0;
}
Solution
In the code given in question, p is a pointer to an int array. list is an int array. In main, the variable p is assigned the return value of the reverse function. The reverse function receives an argument which is the address of the array and number of elements in the array. After performing an in-place reversal of the elements, the function returns back the same array address. So in main, the variable p receives the address of the orginal array (but now storing elements in reverse order).
So both p and list are referring to the same single int array.
=================
Now, to modify code of reverse so that it creates new array to store the reverse... The following code is given.
#include <iostream>
using namespace std;
int* reverse(int* list, int size)
{
int *revArray = new int[size]; //allocate memory to hold the reverse array
for (int i = size - 1, j = 0; i >= 0; i--, j++)
{
revArray[j] = list[i]; //assign each element in reverse
}
return revArray; //return address of reverse array
}
void printArray(int* const list, int size)
{
for (int i = 0; i < size; i++)
cout << list[i] << \" \";
}
int main()
{
int list[] = {1, 2, 3, 4, 5, 6};
int* p = reverse(list, 6);
printArray(p, 6);
return 0;
}
This time, in reverse() function, a new array is allocated space which stores the elements in reverse order. The original list is not changed. The address of the new array is returned. So, in main, the variable p now hold the address of the newly allocated array and NOT the original array. In the first code given in question, the original list itself was modified
![IN C++: using namespace std; int* reverse(int* list, int size) { for (int i = 0, j = size - 1; i < j; i++, j--) { // Swap list[i] with list[j] int temp = lis IN C++: using namespace std; int* reverse(int* list, int size) { for (int i = 0, j = size - 1; i < j; i++, j--) { // Swap list[i] with list[j] int temp = lis](/WebImages/33/in-c-using-namespace-std-int-reverseint-list-int-size-for-i-1096736-1761578505-0.webp)
![IN C++: using namespace std; int* reverse(int* list, int size) { for (int i = 0, j = size - 1; i < j; i++, j--) { // Swap list[i] with list[j] int temp = lis IN C++: using namespace std; int* reverse(int* list, int size) { for (int i = 0, j = size - 1; i < j; i++, j--) { // Swap list[i] with list[j] int temp = lis](/WebImages/33/in-c-using-namespace-std-int-reverseint-list-int-size-for-i-1096736-1761578505-1.webp)