简体   繁体   English

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

[英]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. 我在头文件中声明了int大小和字符串* ptr。 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. 我原本以为这是一个越界问题,但是在看了这篇文章之后 ,我将初始分配固定为size + 1,但是持久性问题似乎证明是相反的。

Changing the value of size does not change the size of the array. 更改size的值不会更改数组的大小。

You allocate an array of size 1. Then you assign something to the first (only) element of that array. 您分配一个大小为1的数组。然后,向该数组的第一个(唯一)元素分配一些内容。 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. 另请注意,使用new不会分配动态数组。 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." Sid S所述 ,“更改size的值不会更改数组的大小。”

And for your "inefficient" concern, a common trick that reflect to PaulMcKenzie and Daniel H 's idea, is to use the doubling strategy . 对于您的“效率低下”问题, PaulMcKenzieDaniel H的想法反映出一个常见的技巧是使用加倍策略 See the following C code for an simple idea: 请参阅以下C代码以获取一个简单的想法:

#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. 这样,您不必每次都添加元素就进行重新realloc ,而是平均可以减少运行时间。

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 ++ . 代替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];
    }

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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