take a look at this code:
Code:#ifndef __LIST_H__ #define __LIST_H__ template <class C> class list; template <class C> class cnode { C data; cnode *next; public: cnode() { data = 0; next = 0; } friend class list<C>; }; template <class C> class list { cnode<C> *head; long lsize; public: list() { head = 0; lsize = 0; } ~list() { this->clear(); } void add(C c) { lsize++; cnode<C> *ptr = new cnode<C>; ptr->data = c; ptr->next = head; head = ptr; } long size() { return lsize; } void clear() { lsize = 0; cnode<C> *ptr = new cnode<C>; cnode<C> *prev = new cnode<C>; ptr = head; while(ptr) { prev = ptr; ptr = ptr->next; delete prev; } head = 0; delete ptr; } C at(long l) { long index = lsize-1; cnode<C> *ptr = new cnode<C>; ptr = head; while(index > l && ptr) { ptr = ptr->next; index--; } return ptr->data; } }; #endif // __LIST_H__The list works as expected with the integers and constant strings.Code:#include <iostream> #include <cstdio> #include "list.h" using namespace std; int main() { char szBuffer[32]; list <char*> lc; list <int> li; int i; int x = 0; li.add(x); x = 2; li.add(x); for(i = 0; i < li.size(); i++) cout << li.at(i) << endl; cout << endl; lc.add("string 1"); lc.add("string 2"); lc.add("string 3"); for(i = 0; i < lc.size(); i++) cout << lc.at(i) << endl; cout << endl; lc.clear(); scanf("%s", szBuffer); lc.add(szBuffer); scanf("%s", szBuffer); lc.add(szBuffer); scanf("%s", szBuffer); lc.add(szBuffer); for(i = 0; i < lc.size(); i++) cout << lc.at(i) << endl; return 0; }
On the last part, the list doesn't print three unique strings since
there is just a reference to szBuffer so it prints copies of the last
string entered.
Is there a way to make sure that a copy of the string is added
to the list rather than a reference, other than having separate
buffers for every string?




Reply With Quote