0

I started to learn c++, and I'm trying to understand the arrow feature in c++. I have this example code, but I'm not getting the desired output.

#include <iostream>
#include <chrono>
struct student {
    int age;
};

student* getStudent(int age ){
    student person;
    student *p;
    p = & person;
    p->age = age;
    return p;
};

int main(int argc, const char * argv[]) {
    auto* d = getStudent(29);
    std::cout << d->age <<std::endl;
    std::cout << d->age <<std::endl;
    return 0;
}
Output
29
-2003661472
Program ended with exit code: 0

Why am I getting this undesired output?

David
  • 105
  • 1
  • 10
  • 2
    you return the address of a variable that is destroyed by the time you go to use the variable – M.M Dec 24 '20 at 06:08
  • You return a pointer to the `person` object that existed while `getStudent` was running. But then you try to dereference that pointer when `getStudent` is not running. No `student` object exists at that point since `person` went out of scope. So there is no person whose age you can print. A pointer to an object is only useful during that object's lifetime and may not be dereferences after the object it pointed to is gone. – David Schwartz Dec 24 '20 at 06:10
  • If you compile your code with at least some basic and essential flags, you could save a lot of time. Compilers can catch this sort of thing easily in such cases. Please check out your compiler's manual page and get into a good compiling routine. – costaparas Dec 24 '20 at 06:28

0 Answers0