#include <iostream> using namespace std; struct Foo { int data; Foo* next; }; void foo1(Foo**, int); void foo2(Foo**, int); int main() { Foo *bar1 = NULL; Foo *bar2 = NULL; foo1(&bar1, 55); foo2(&bar2, 44); cout << bar1->data << endl; cout << bar1->next << endl; // почему введет какой-то адрес, а не NULL? cout << bar2->data << endl; cout << bar2->next << endl; return 0; } void foo1(Foo** bar, int data) { Foo foo; foo.data = data; foo.next = NULL; if( *bar == NULL) { *bar = &foo; } } void foo2(Foo** bar, int data) { Foo *foo = new Foo; foo->data = data; foo->next = NULL; if( *bar == NULL) { *bar = foo; } } |
1 answer
Probably because foo1 returns the address of a temporary variable on the stack. After the function ends, this address is almost guaranteed to be occupied by other variables or parameters of another function.
- Why then is the
bar1->datavaluebar1->data? - jisecayeyo - 2@jisecayeyo, coincidence. The stack has not changed in that place simply. - ixSci
- That is, is
fooin the functionfoo1just a local one, which is "destroyed" after the function is completed? - jisecayeyo - 2Yes, and her address will be busy when needed. - Ildar Khairullin
|