"using only pointers" is a pretty vague requirement. The following, modern solution in a certain way also uses "only pointers", because std::rotate
operates on iterators and pointers are iterators:
#include <algorithm>
#include <iostream>
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
using std::begin;
using std::end;
std::rotate(begin(arr), end(arr) - 1, end(arr));
for (auto&& element : arr)
{
std::cout << element << "\n";
}
}
Yet I feel that the teacher who gave you this assignment would not be happy with it for some reason. As for your solution:
int *ptr = arr; //initialize to first element
int *ptr2 = arr+1; //initialize it to second element
while (n >0) // keep doing it until size is done with
{
*ptr2 = *ptr;
++ptr2;
ptr ++;
n--;//
}
(I will assume that your n
is 4 before the loops begins, because otherwise you will have more than 4 iterations and run into undefined behaviour in the last one.)
In the first iteration of the loop:
arr[1]
becomes arr[0]
.
ptr2
is made to point to arr[2]
.
ptr
is made to point to arr[1]
.
Array after first iteration: [1, 1, 3, 4, 5]
As you can see, at this point, the element containing value 2 is already lost.
In the second iteration of the loop:
arr[2]
becomes arr[1]
.
ptr2
is made to point to arr[3]
.
ptr
is made to point to arr[2]
.
Array after second iteration: [1, 1, 1, 4, 5]
Now the element containing value 3 is also lost. The pattern is now clear; you are "losing" all elements and are simply overwriting everything with 1s.
You must find a way to conserve the elements you are overwriting. Or preferably just use std::rotate
.