tags:

views:

45

answers:

2
class student
{
 char *name;
 int I;
 public:
 student()
 {
  I=0;
  name=new char[I+1];
 }
 student(char *s)
 {
  I=strlen(s);
  name=new char[I+1];
  strcpy(name,s);
 }
 void display()
 {
  cout<<name<<endl;
 }
 void manipulate(student &a,student &b)
 {
  I=a.I+b.I;
  delete name;
  name=new char[I+1];
  strcpy(name,a.name);
  strcpy(name,b.name);
  }
 };
 void main()
 {
  clrscr();
  char *temp="Jack";
  student name1(temp),name2("Jill"),name3("John"),S1,S2;
  S1.manipulate(name1,name2);
  S2.manipulate(S1,name3);
  S1.display();
  S2.display();
  getch();
 }

i calculated the ouput of this code many times but couldn't understand it. Output of this code is: Jill endline John

A: 

Possibly you want strcat instead of second strcpy in the manipulate function.

Alex Farber
A: 

Your problem is here:

strcpy(name,a.name); strcpy(name,b.name);

Will copy Jack+null into the first five bytes of name, and then the second strcpy copies Jill over those same bytes. Then in the second case likewise John is copied over the initial bytes.

You probably want to use strcat?

djna