使用指针的问题与动态数组 [英] Problems using pointers with an dynamic array
问题描述
我从读infile中整数和使用指针将它们添加到一个int数组。
I am reading integers from an infile and adding them to an int array using pointers.
我已经通过code多次,一切似乎符合逻辑跟踪,我没有得到任何语法错误或警告的编译器,我不知道什么是错的。
I have traced through the code multiple times and everything seems to flow logically and I am not getting any syntax errors or warnings in the compiler so I'm not sure what's wrong.
该计划要求我们使用数组而不是载体,否则我不认为我会被有这些问题。
This program requires us to use arrays and not a vector or else I don't think I would be having these problems.
现在我的输出是阅读各种扭曲。我知道它与指针做,但我在此刻损失。
Now my output is reading all kinds of screwy. I know it has to do with the pointers but I am at a loss at the moment.
INFILE:
3
456
593
94
58
8
5693
211
输出:
The items in the array are as follows.
7476376, 7475472, -17891602, 17891602, -17891602, -17891602, -17891602, -178916
collections.h
collections.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
对不起,我知道这可能很简单,但对我的生活我看不到的问题。
Sorry, I know this might be simple but for the life of me I can't see the problem.
推荐答案
您意外宣布的本地副本阵列
将覆盖类的成员:
You accidentally declared a local copy of array
which overrides the class member:
//new master array
delete [] array;
int *array = new int[arraySize];
^^^^^
删除为int *
从最后一行,其余的看起来不错。
Remove the int *
from that last line and the rest looks okay.
PS:你有没有使用的std ::矢量&lt考虑; INT&GT;
PS: Have you considered using std::vector<int>
?
这篇关于使用指针的问题与动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!