Having trouble implementing my own reserve function. ( have to do it for an assignment)

Here is what i have so far but it doesn't appear to work.


.h prototype

void reserve(size_type n);

constructor for our string

mystring::mystring(const char * s) {
len = strlen(s);
buf_size = len + 1;
ptr_buffer = new char[buf_size];
strcpy(ptr_buffer, s);

}

reserve function:

void mystring::reserve(size_type n){
     
     if(n > buf_size){
       char *hold = ptr_buffer;
       delete ptr_buffer;
       ptr_buffer = new char[n+1];
       ptr_buffer = hold;
       delete hold;
       buf_size = n+1;
       }
     
     }

n is size_type unsigned int

The .h was supplied and we cannot change it.

I'm not really sure what you think the code you have means, but to me it is a little bit silly.

void mystring::reserve(size_t n) {
  if(!n>buf_size) return;
  char *swap = new char[n]; // also it's better to use powers of 2 to prevent overhead
  memcpy(swap,ptr_buffer,buf_size); // copy the old data
  buf_size = n; // this is the new maximum occupancy of the array
  delete[] ptr_buffer; // delete the old array, as it will soon just be random memory
  ptr_buffer = swap; // change your char* to the address swap points to
  // which is the array we just allocated and copied the old contents into
}

You really need to read up on pointers and dynamic memory.
Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.