将指针与动态数组一起使用时出现问题
Problems using pointers with an dynamic array
我正在从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
对不起,我知道这可能很简单,但对于我的生活,我看不到问题所在。
您不小心声明了覆盖类成员的array
的本地副本:
//new master array
delete [] array;
int *array = new int[arraySize];
^^^^^
从最后一行中删除int *
,其余部分看起来没问题。
PS:你考虑过使用std::vector<int>
吗?
相关文章:
- 如何将GTest与CMake一起使用?遵循谷歌指南时的链接问题
- 在浮点精度成为一个问题之前,可以将多少个浮点值加在一起
- 将cpp_redis pub/sub与条件变量一起使用时出现问题
- 在本地安装OpenMPI的问题与CUDA一起使用
- 与自定义命名空间一起使用时实现 std::error_category、名称解析问题
- 与lambda一起使用虚拟继承在初始化列表中捕获此问题的GCC错误
- 将 cplex 与 netbeans c++ 一起使用,链接器问题
- 将双缓冲位图与 AlphaBlend 一起使用时出现的问题
- 有关将智能指针与 Winsock 的 addrinfo 结构一起使用的问题
- QT TreeView问题与排序模型一起使用
- 将模板气泡排序与结构数组一起使用时出现问题
- 将 boost/thread headers 与 clang++ (Windows) 一起使用时出现问题
- 将 Botan 与 Qt 一起使用时遇到问题
- 与私人成员一起上课.这个代码出了什么问题
- 将指针与动态数组一起使用时出现问题
- 将问题与多个文件链接在一起
- Clang:将绑定或mem_fn与字符串::c_str和转换一起使用时出现问题
- 将get_value与 Boost 的属性树一起使用时遇到问题
- 将字符串与 sprintf() 函数一起使用时出现问题
- 将矢量与函数一起使用,指针问题