分配一个零数组

时间:2014-02-28 18:31:08

标签: c++ arrays numbers zero

我正在尝试在二十个零的数组的第五个实例中创建一个单独的5。我确实得到了我想要的5个,但这样做会导致四个额外的零跟随将数组计数提高到24.导致这种情况发生的原因是什么?我已经尝试了一切,改变它给了我垃圾值。

#include <cstring>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;

class PartFilledArray
{
public:
    PartFilledArray(); //create instance
    PartFilledArray(int array_size); //declares the sizes of arrays being added

    //Overloading Assignment Operator
    PartFilledArray operator = (const PartFilledArray& other)
    {
        if(this == &other) return *this; // handling of self assignment
        delete[] a; // freeing previously used memory
        double a[20];
        int _size = number_used; memcpy(a, other.a, sizeof(int) * _size);
        return *this;
    }
        void add_value(double new_entry); 
        void print_array(); 

    //copy constructor
    PartFilledArray::PartFilledArray( const PartFilledArray& other )
    {
        max_number = other.max_number;
        number_used = other.number_used;
    }

    //deconstructor
    ~PartFilledArray()
    {
        //delete [] a; 
    } 

protected:
    double a[20]; //declares first array 
    int max_number;
    int number_used;
};
#endif  

//Precondition: an array of 20 elements must all equal 0. 
//Postcondition: This fifth element in the array will take the value of 5.

int main ()
{
    PartFilledArray instance(20);
    instance.print_array();

    int new_entry = 5; //declares at the fifth element
    int array_size = 20;

    instance.add_value(new_entry);
    instance.print_array();

    system ("pause");
    return 0;
}

PartFilledArray::PartFilledArray(int array_size) : max_number(array_size), number_used(0) 
{
    {
        for (int i = 0; i < array_size; i++)
        {
            a[i] = 0; // adds element in array
        }
    }

} 

void PartFilledArray::add_value(double new_entry)
{
    a[number_used] = new_entry;
    number_used = number_used + 1;
}

void PartFilledArray::print_array()
{
    for (int i = 0; i < 20; i++)
    {
        cout <<  a[i] << endl; //prints the array of elements
    }
}

1 个答案:

答案 0 :(得分:0)

add_value()正在向数组的末尾添加一个条目(超出您分配内存的位置)。然后增加元素数量。

这就是你的数组似乎增长的原因。事实上,你正在超越分配的内存。

要完成您想要的任务,您需要将add_value界面更改为如下所示:

void PartFilledArray::add_value(int offset, double new_entry)
{
    a[offset] = new_entry;
}

当然,良好的编程会指示您检查偏移量以确保它不会超出您的阵列。