2

infile から整数を読み取り、ポインターを使用して int 配列に追加しています。

コードを何度もトレースしましたが、すべてが論理的に流れているように見え、コンパイラで構文エラーや警告が表示されないため、何が問題なのかわかりません。

このプログラムでは、ベクトルではなく配列を使用する必要があります。そうしないと、これらの問題は発生しないと思います。

今、私の出力はあらゆる種類の厄介なものを読んでいます。ポインターに関係していることは知っていますが、現時点では途方に暮れています。

インファイル:

3
456
593
94
58
8
5693
211

出力:

The items in the array are as follows.
7476376, 7475472, -17891602, 17891602, -17891602, -17891602, -17891602, -178916

コレクション.h

class collections
{
    public:
        collections();
        void add(int);  //adds the value to the array.
        void print();  //prints item of the array comma separated.
        ~collections();
    protected:
        int arraySize;
        int *array;
};

コンストラクタ:

collections::collections()
{
    arraySize = 1;
    array = new int[arraySize];
}//done

ボイド追加:

void collections::add(int value) //adds the value to the array.
{
    //initial add to master array.
    if (arraySize == 1)
    {
        array[0] = value;
        arraySize++;
    }

    //every other add to master array.
    else
    {
        //temp array.
        int *tempArray = new int[(arraySize)];

        //copies old array into temp array.
        for (int i = 0; i < arraySize-1; i++)
        {
            tempArray[i] = array[i];
        }

        //adds new incoming value to temp array.
        tempArray[(arraySize-1)] = value;

        //new master array
        delete [] array;
        int *array = new int[arraySize];

        //copies temp to master array.
        for (int j =0; j < arraySize; j++)
        {
            array[j] = tempArray[j];
        }

        //cleanup
        delete [] tempArray;
        arraySize ++;
    }
} //done

ボイドプリント:

void collections::print() //prints item of the array comma separated.
{
   cout << "The items in the array are as follows.\n";
    for (int i = 0; i < arraySize; i++)
    {
        cout << array[i] << ", ";
    }
}//done

申し訳ありませんが、これは単純かもしれませんが、私の人生では問題がわかりません。

4

1 に答える 1