-3
#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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
beryllium
  • 63
  • 1
  • 1
  • 7

1 Answers1

0

new char[] doesn't compile under GCC. :) new char[20], however, does.

char[20] tells the compiler that you want 20 characters in an array. This is typically allocated on your call stack. Very large allocations can cause stack overflows so this is discouraged in some circles.

If you use new you must call delete[] name or you will have a memory leak. If you call delete name you will have an error in your code because the array will not be deleted, only that one char *.

Sam
  • 2,939
  • 19
  • 17