hi to al
i was doin some programming till i encountered this problem in the followin code...
i am nt able to find anythn wrong with the code bt it's nt showing the right result.


#include<iostream>
#include<conio.h>
using namespace std;
class person
{
char* name;
public:
void get()
{
cout<<"enter name=";
cin>>name;
}
void show()
{
cout<<name<<endl;
}
};
int main()
{
person* p[10];
int n=0;
char choice;
do
{
p[n]=new person;
p[n]->get();
n++;
cout<<"enter another(y/n):";
cin>>choice;
}while(choice=='y');
for(int i=0;i<n;i++)
{cout<<"person "<<(i+1)<<" is ";
p->show();
}

getch();
return 0;
}

it's actually showing the data entered fr the last object even at place of the other objects.....thanx in advance

Your not allocating any memory for the member variable name.

This would work better if you define name as a std::string.

Edited 6 Years Ago by gerard4143: n/a

You are not allocating any space for the name var in your person class.
Change :

char* name;
public:
void get()

to:

char name[80]
public:
void get()

yeah,i tried that and it worked just fine......
bt for the love of pointers i want to do it using pointer notation for the data members of class like i tried to do in the code........can u help me with that as well.....

Well, somehow you need to allocate memory for the data you enter, on the stack or on the heap. If you want to try the head, do something like this

class person
{
char *name;
public:
person()
{
name = new char[80];
}

As you see, I've added av constructor to the person class, and memory is allocated on the heap and is pointed to by the name pointer.

This article has been dead for over six months. Start a new discussion instead.