为什么我的C++程序停止工作

  • 本文关键字:C++ 程序 停止工作 c++
  • 更新时间 :
  • 英文 :


我在vs代码中编写了C++程序,当我运行它时,它要求我输入元素值,但当我第二次输入时,它已经停止工作。我不知道问题出在哪里,但如果你知道,请帮我解决这个问题。

#include <iostream>
using namespace std;
class myArray {
public:
int total_size;
int used_size;
int* ptr;
myArray(int tsize, int usize)
{
total_size = tsize;
used_size = usize;
ptr = new int(tsize);
}
myArray() {}
void setvalue()
{
int n;
for (int i = 0; i < used_size; i++) {
cout << "Enter the element" << endl;
cin >> n;
ptr[i] = n;
}
}
void show()
{
for (int i = 0; i < used_size; i++) {
cout << "The element in array" << endl;
cout << ptr[i] << endl;
}
}
};
int main()
{
myArray(10, 2);
myArray a;
a.setvalue();
a.show();
return 0;
}

您使用了used_sizeptr,但没有在a.setvalue();a.show();中初始化它们。

看来

myArray(10, 2);
myArray a;

应该是

myArray a(10, 2);

此外,正如@Yksisarvien所指出的,

ptr = new int(tsize);

应该是

ptr = new int[tsize];

以分配一个数组而不是单个CCD_ 5。

最新更新