The first part of the code is List.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //********************************************** // List.h //********************************************** #ifndef LIST_H #define LIST_H #include #include using namespace std; class List{ public : List();//Constructor ~List();//Destructor void addItem(int item);//add integer item void deleteItem(int loc);//delete item private: int *ptr,size;//pointer and its size }; #endif |
This part of the code is List.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #include "List.h" List::List(){ size = 0;//We inialize size to 0 //since initial size is 0 } //addItem method which adds an item to //the end of the list just like arrayList void List::addItem(int item){ //if size is 0 create an array if(size==0){ ptr= new int[++size]; ptr[size-1] = item; } //if size is not zero else{ //we inialize a pointer which have size //of size+1 since we want to add one more //item to the end of the list int *newPtr; newPtr = new int [size+1]; //we put the elements into new array for(int i=0;i<size;i++) newPtr[i] = ptr[i]; //we lastly insert the item to the end of //the list newPtr[size++] = item; //we delete the ptr pointer's elements //since they use memory delete [] ptr; //Lastly we use address of newPtr for ptr ptr = newPtr; } } //deleteItem method which deletes an item by given //location which specify array position. void List::deleteItem(int loc){ //we inialize a pointer which have size //of size-1 since we want to delete one //item which is on location loc int *newPtr; newPtr = new int [size--]; //we put the elements into newPtr until //we come accross to the given location for(int i=0;i<loc-1;i++) newPtr[i] = ptr[i]; //after that we do not put the ptr[loc] //so that it will be deleted for(int i=loc;i<size;i++) newPtr[i] = ptr[i+1]; //we delete the ptr pointers' elements //since they use memory delete [] ptr; //Lastly we use address of newPtr for ptr ptr = newPtr; } //Destructor List::~List(){ //we delete the ptr pointers' elements //since they use memory delete [] ptr; } |
Are you sure the “delete[], delete” thing is not wrong? Something tells me this is a double delete on the same pointer. Also, this class could benefit if you allocated memory in chunks (have a “size” member and “allocated_size”, allocate e.g. 1024 bytes more when when “size” >= “allocated_size” and vice versa when freeing memory).
Thank you very much for your attention. The first delete [] ptr is to delete array elements. The second one is not necessarry and we delete ptr. Yout are right about “size” and “allocated_size”. However, I wanted to show people the use of pointers and I did not care efficiency. It will be more beneficial if we use chunks.
Thank you very much…