Quote:
Originally posted by 7stud
Hi,
void read_data(item* pitem)
{
const int MAX = 20;
char name[MAX];
cout<<"Enter your name: ";
cin.getline(name, MAX);
cout<<name<<endl; //successful output
pitem->pname = name;
cout<<pitem->pname<<endl; //successful output
cout<<"Enter your number: ";
cin>>pitem->number;
return;
}
void print_data(item* pitem)
{
cout<<"Here is the name you entered:\n";
cout<<pitem->pname<<endl; //****failure: prints out strange symbols
return;
}
[/code] |
The same thing bit me when I was learning C after having been spoiled by Turbo Pascal's handling of strings.
In C/C++, array names are pointers; hence:
char name[20];
char *cp = name; // pointer cp now points to name[0]
Therefore, when you assign one character array to another as in:
pitem->pname = name;
you are making pname point to the string in name. You have not copied the string into pname.
Why it works in read_data() and not in print_data() is because the data, name, is declared locally in read_data() and so still exists. But as soon as you exit read_data(), name goes away. So when you try to output in print_data(), the data no longer exists and pname is pointing to who-knows-what.
Possible solutions:
1. Declare name to be global, so that it will persist between function calls. However, that would make pname superfluous.
2. When you've read in a string for name, dynamically allocate space for it and pointed to by pname, and copy the string from name to pname. Make sure to clean up (ie, delete that allocated space) when you exit the program -- not absolutely necessary in your example, but good practice for avoiding memory leaks in larger projects. Eg:
Code:
cout<<name<<endl; //successful output
pitem->pname = new char[strlen(name)+1];
strcpy(pitem->pname,name); // now pname has copy of string
I'm sure that Solution #2 is what you are looking for.
PS
Space for local variables in a function is allocated on the stack as you enter the function and is removed from the stack when you leave.