I recently ran into an issue while experimenting with linked lists. When I use a function to link up a new node that has a string in its data field it doesn't work. By this I mean that when the function (linkin() see below) returns , the string (which was local to the function) is destroyed and so the string field appears to be uninitialized.
However, when I do this exact same operation with an int it seems to work just fine. The code I used is below (its the int version, but make val a string instead of an int to see the other version). Could someone explain to me what is happening?
Thanks!
struct testlist {
int val;
testlist *next;
};
void linkin ( testlist *a );
int main() {
testlist test;
linkin(&test);
cout << test.next->val <<endl;
}
void linkin ( testlist *a )
{
testlist b;
b.val=1;
a->next = &b;
cout << a->next->val <<endl;
}