C++ making int array using new operation -
i want make dynamic array using new operator.
#include <iostream> using namespace std; class set{ public: set() { count = 0; } set(int i) { elements = new int; elements[0] = i; count = 1; } void add(int new_element) { if(find(new_element) != -1) { cout << "the set has " << new_element << " already.\n"; return; } else { // elements[count] = new int; elements[count++] = new_element; cout << elements[count-1] << endl; } } void remove(int remove_element) { int index = find(remove_element); if(index == -1) { cout << "the set doesn't have " << remove_element << ".\n"; return; } else { for(int i=index ; i<count ; i++) elements[i] = elements[i+1]; count--; } } void enumerate() { for(int i=0 ; i<count ; i++) cout << elements[i] << " "; cout << endl; } ~set() { } private: int* elements; int count; int find(int temp_element) { int i=0; for( ; i<count ; i++) if(elements[i] == temp_element) return i; return -1; } }; int main() { set s1(1); s1.add(2); s1.add(3); s1.remove(2); s1.add(4); s1.add(5); s1.enumerate(); return 0;
i know using stl makes problem easier. but, want know why code making error. and, don't know why works without line 18. @ last, how can free allocated storage? please, let me know answer.
you declared elements
pointer int
. meains elements[i]
plain int
. writing
elements[count] = new int;
your attempting assign pointer newly allocated int it. it's not working because elements[count]
int
, not pointer.
as freeing allocated storage, std::vector
keeps track how many elements contains lets use n
. data[0]
data[n-1]
actual information. if had more storage @ end, leaves there without deallocating , trash value , doesn't let access it. can resize making new array new size, copying every element on old storage, calling delete[]
on old pointer. watch out possible memory leaks though.
Comments
Post a Comment