#include<iostream>
#include<process.h>
using namespace std;
template<class T>
class List{
class Node{
public:
T num;
Node*next;
}*head,*tail;
public:
List(){
head = tail = NULL;
}
void insert(T *n){
Node*tmp=new Node;
tmp->next = head;
tmp->num = *n;
head = tmp;
if (tail == NULL){
tail = tmp;
}
}
void append(T*n){
Node*tmp=new Node;
tmp->next=NULL;
tmp->num = *n;
if (tail == NULL){
head = tail = tmp;
}
else {
tail->next = tmp;
tail = tmp;
}
}
T Get(){
if (head == NULL){
exit(0);
}
else{
T t = head->num;
Node*p = head;
if (head->next == NULL){
head = tail = NULL;
}
else{
head = head->next;
}
delete (p);
return t;
}
}
};
class person{
public:
char*name=new char[];//problem lies here!
//char name[20];
int age;
float hight;
person(){}
};
int main(){
person a;
List<int>link1;
List<person>link2;
for (int i = 0; i < 5; i++){
cin >> a.name >> a.age >> a.hight;
link2.insert(&a);
link1.append(&i);
}
for (int i = 0; i < 5; i++){
a = link2.Get();
link2.append(&a);
cout << a.name << " " << link1.Get() << endl;
}
}
As the explanation goes in the code, when using char*name=new char[]
to replace char name[20]
, the program went wrong. It wouldn't output all the names as expected, but only print the last input name 5 times. So what's the difference between these two expressions?
Thanks a lot.