Regarding pointer and return value

#include

using namespace std;

int* test(){

int s[ ]={20,12,21,31};

int *ptr{s};

return ptr;

}

int main(){

int *p=test();

cout<<*(p+2); //returns 21

}
The output is 21 but since after function call the memory in which array is stored locally is destroyed, then how does the pointer access it and produce 21 as output??

you can’t access all elements
only one will be accesed because of compiler functioning

if you do this
for(int i=0;i<4;i++) cout<<*(p+i)<<endl;

you can see this only one will give correct output

if you have more doubts regarding this feel free to ask
i hope this helps
if yes hit a like :heart:: and don’t forgot to mark doubt as resolved :grinning:

why even one correct answer is coming, ideally it should not give even one correct answer

ideally yes but it’s compiler functioning

may be the function destroying take some time and happens little later

So in such cases is it better to use dynamic array??

yes dynamic array are beneficial in this scenario