#include <iostream> using namespace std; int* flipArray(int input[], int n) { int output[n]; int pos = 0; for (int i = n-1; i >= 0; i--) { output[pos++] = input[i]; } int* p = output; for (int k = 0; k < n; k++) cout << *pk << endl << endl; return p; } int main() { const int SIZE = 5; int firstArray[SIZE]; for (int n = 0; n < SIZE; n++) { firstArray[n] = n+1; } int* a; a = flipArray(firstArray, SIZE); for (int j = 0; j < SIZE; j++) cout << *aj << endl; cout << endl; cout << *a << '\t' << *a+1 << '\t' << *a+2; return 0; }
I'm trying to flip firstArray with a function that returns a pointer, but I'm trying to understand how index access works with a pointer.
This is why I am confused: Inside the flipArray function, the following for loop:
for (int k = 0; k < n; k++) cout << *pk << ' ';
displays "5 4 3 2 1" on the console. I realized that I had to access the element of the vector with *(p+k) , not *(pk) . If I type *(p+k) , "5 6 7 8 9" is printed on the console. If I print an array without pointers and using k as the index location, "5 4 3 2 1" is printed to the console.
In my main function, however, the * a values ββthat are assigned the p pointer from the flipArray function do not get the same results:
for (int j = 0; j < SIZE; j++) cout << *aj << endl;
prints 5 0 -1 -2 -3 to the console and
for (int j = 0; j < SIZE; j++) cout << *a+j << endl;
prints 5 2 3 4 5 to the console.
In addition, I thought that the location of the *p pointer and *a location pointer should be the same! But when I print the address &p in the function, I get the location 0x28fde0, and when I print the address &a basically, I get the location 0x28fedc. Of course, this was done during the same run.
Can someone tell me where I went astray Thanks!
Thanks to everyone for the informative answers.
I updated my solution and now it returns what I expect. I have a new question about memory leak, and when to remove pointers.
int* flipArray(int input[], int n) { int* output = new int[n]; int pos = 0; for (int i = n-1; i >= 0; i--) output[pos++] = input[i]; return output; } int main() { const int SIZE = 5; int firstArray[SIZE]; for (int n = 0; n < SIZE; n++) { firstArray[n] = n+1; } int* a; a = flipArray(firstArray, SIZE); for (int j = 0; j < SIZE; j++) cout << a[j] << " ";
Will pointer output be deleted when the flipArray function returns? If not, how do I remove the output and also return it? Does the pointer a in my main function delete the same as deleting the output, because they point to the same location?