动态数组在构造函数中崩溃

时间:2018-01-15 05:38:17

标签: c++ dynamic-arrays

我试图为教育目的实现动态字符串数组。我遇到的问题是每当我尝试在构造函数中向空数组添加字符串时程序就会崩溃。

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

我在头文件中声明了int size和string * ptr。我最初认为这是一个越界问题,但在查看this post后,我将初始分配修改为大小+ 1,但持续存在的问题似乎证明不是这样。

3 个答案:

答案 0 :(得分:3)

更改size的值不会改变数组的大小。

您分配一个大小为1的数组。 然后,您将某些内容分配给该数组的第一个(唯一)元素。 然后你给那个数组的第二个元素赋值 - 但是数组只有一个元素。

另请注意,使用new不会分配动态数组。分配后,尺寸无法改变。

答案 1 :(得分:3)

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.

答案 2 :(得分:0)

而不是string使用pointer并且每次动态分配内存时他们不需要0然后++

 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];
    }

我希望它有所帮助。