c++ array rev pointer

To reverse an array using a pointer in C++, you can follow these steps:

  1. Declare an array and initialize it with some values.
  2. Create two pointers, one pointing to the start of the array and the other pointing to the end of the array.
  3. Use a loop to swap the values of the elements pointed by the two pointers.
  4. Increment the first pointer and decrement the second pointer in each iteration of the loop.
  5. Repeat the loop until the first pointer becomes greater than or equal to the second pointer.

Here's an example code snippet that demonstrates this process:

#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    int *start = arr;
    int *end = arr + size - 1;

    while (start < end) {
        // Swap the values pointed by start and end
        int temp = *start;
        start = end;
        *end = temp;

        // Move the pointers
        start++;
        end--;
    }

    // Print the reversed array
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

In this code, we first declare an array arr with some initial values. Then, we calculate the size of the array using the sizeof operator and store it in the size variable.

Next, we create two pointers start and end. The start pointer points to the beginning of the array (arr) and the end pointer points to the end of the array (arr + size - 1).

We then enter a while loop that continues until the start pointer becomes greater than or equal to the end pointer. Inside the loop, we swap the values pointed by start and end using a temporary variable temp. After swapping, we increment the start pointer and decrement the end pointer.

Finally, we print the reversed array by iterating over the arr array using a for loop.

When you run this code, it will output the reversed array: 5 4 3 2 1.