This question already has an answer here:
I am trying to pass an array out of a function using pointers. When I dereference the pointer inside the function, it gives the correct value, but when it is dereferenced in the main function, it gives a wildly different value.
#include <iostream>
using namespace std;
int* func() {
int arr[4] = {0,1,2,3};
int* ptr = arr;
cout << ptr << endl;
cout << *ptr << endl;
return ptr;
}
int main()
{
int* ptr;
ptr = func();
cout << ptr << endl;
cout << *ptr << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire