简体   繁体   English

在 C++ 中为动态数组创建值构造函数时遇到问题

[英]Facing issues while creating value constructor for dynamic array in C++

I am writing following code.我正在编写以下代码。

BiArray::BiArray(int arr[], int size)  {
    // IMPLEMENT ME
    arrsize_ = size;
    if (arrsize_*LO_THRESHOLD > INITIALCAP)
    {
    capacity_= arrsize_*LO_THRESHOLD;
    } else {
    capacity_= INITIALCAP;
    }
    position_ = ((capacity_ - arrsize_)/2 )-1;
    intrnlArr_ = new int[capacity_];
    for (int i=1; i < arrsize_; i++)
    {
    int a = i-1;
    intrnlArr_[i+position_]= arr[a];
    } 
}

It compiles but when I run a test in the following code I get a segmentation fault.它编译但是当我在下面的代码中运行测试时我得到了一个分段错误。

在此处输入图像描述

void BiArrayTester::testValueCtor() {
    funcname_ = "BiArrayTester::testValueCtor";

    int arr1[1] = {0};
    BiArray a1(arr1,1);
    if (a1.getSize() != 1 || a1.getCapacity() != INITIALCAP)
        errorOut_("size-1 value constructor incorrect size or capacity",1);
    if (a1[0] != 0) errorOut_("size-1 value constructor incorrect content",2);

    int arr2[10] = {0,1,2,3,4,5,6,7,8,9};
    BiArray a2(arr2,10);
    if (a2.getSize() != 10 || a2.getCapacity() != 30)
        errorOut_("value constructor incorrect size or capacity",3);
    for(int i=0;i<10;i++)
        if (a2[i] != i) errorOut_("value constructor incorrect content",4);

    passOut_("Tested the value constructor.");
}

Please help me to figure out my fault.请帮我找出我的错。

Segmentation fault is caused by this line intrnlArr_[i+position_]= arr[a];段错误是由这一行引起的intrnlArr_[i+position_]= arr[a]; . . i+position gets greater than capacity_-1 , which is the greatest available index in the array. i+position大于capacity_-1 ,这是数组中最大的可用索引。

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

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