简体   繁体   中英

Dynamic array crashing at constructor

I'm trying to implement a dynamic array of strings for educational purpose. The problem that I ran into is the program crashing whenever I try to add strings to the empty array in my constructor.

Array::Array(string dir, string dim)
{
   size = 0;
   ptr = new string[size + 1];
   ptr[size] = dir;
   size++;
   ptr[size] = dim;
   size++;
}

I have int size and string *ptr declared in my header file. I originally thought this to be a out-of-bounds problem, but after looking at this post , I fixed the initial allocation to size + 1, but the persisting problem seems to prove otherwise.

Changing the value of size does not change the size of the array.

You allocate an array of size 1. Then you assign something to the first (only) element of that array. Then you assign something to the second element of that array - but the array only has one element.

Also note that using new does not allocate a dynamic array. Once allocated, the size can't change.

As mentioned by Sid S , "changing the value of size does not change the size of the array."

And for your "inefficient" concern, a common trick that reflect to PaulMcKenzie and Daniel H 's idea, is to use the doubling strategy . See the following C code for an simple idea:

#include <stdlib.h>

struct MyArray {
    int capacity;
    int size;
    int *data;
}

/* any other functions you would use, eg: create, destroy of MyArray */     

void push(struct MyArray myarray, int n) {

    if (size == capacity) {
        capacity *= 2;
        data = realloc(data, capacity*sizeof(int));
    }

    /* add the element to the end of data and increase size */
}

In this way, instead of doing realloc every time there is an element added, you would have a lower runtime in average.

A detailed amortized analysis about doubling strategy can be found here .

Instead of string use pointer and allocate memory dynamically every time how much they need not 0 and then ++ .

 Array :: Array(char *dir,char *dim)
    {
            int l1,l2;
            l1=strlen(dir);
            l2=strlen(dim);
            /**assume  n1 & n2 are data member of "Array" class.**/
            n1=new char[l1+1];// allocating memory dynamically
            n2=new char[l2+1];
    }

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM