Hello everyone, i'm implementing a string class and i'm having troubles understanding why my erase function displays garbadge.
My plan was to create a new dynamic array called temp which will hold the modified version of the array after the erase. I used memmove/memcopy from the <cstring> to store the new array.
here's my code:
note: memmove's function prototype is:
note: chars is a dynamic array of type char so in the .h file it looks like:Code:memmove(char * dest, const char *source, size_t count); //count is how many bytes it should copy from source and move to destination.
Code:private: char *chars; size_t allocated; //how many elements including the '\0' size_t curr_len; //how many elements excluding the '\0'
The erase function will start deleting at the parm "start" and it will keep deleting until count is reach, so for example if you had:Code:void string::erase (size_t start, size_t count ) { assert (start < length()); char *temp = new char [length()+1]; size_t counter = 0; // Don't try to erase more chars than there are! if (count > length() - start + 1) count = length() - start + 1; for(size_t i = 0; chars[i] != '\0'; i++) { if(i != start) memmove(temp,chars+i,1); //strcat(temp,chars[i]); else if(i == start) { while(counter < count-1) { counter++; ++i; } } }
[A][B][C][D]['\0']
0 1 2 3 4
erase(2,2);
it would start at C and delete C and D and you would be left with:
[A][B][\0']
Thanks.
![]()




Reply With Quote