【发布时间】:2023-04-06 09:36:01
【问题描述】:
我使用 int 指针作为私有指针来访问数组。当我为存储和获取值的数组编写单独的函数时,程序崩溃。但是,如果我在构造函数中编写获取值和存储值代码,则程序可以正常工作。我无法找到问题所在。
程序 1:(不起作用)
#include<iostream>
using namespace std;
class NewArray{
private:
int Size = 0;
int *arrAddr = NULL;
public:
NewArray(int);
void SetValue(int);
void GetValueOf(int);
};
//Array is created
NewArray::NewArray(int arSz){
int arr[arSz];
Size = arSz;
arrAddr = arr;
cout << "An array of Size " << Size << " is created" << endl;
}
// Store Value function
void NewArray::SetValue(int index)
{
cin >> *(arrAddr+(index));
}
//Get value function
void NewArray::GetValueOf(int idx)
{
if ((idx >= Size) || (idx < 0))
{
cout << "index value is out of bound" << endl;
}
else
{
cout << *(arrAddr+idx) << endl;
}
}
int main()
{
int arrSize, arrIdx;
cout << "enter the size of array" << endl;
cin >> arrSize;
if (arrSize > 0)
{
NewArray ar(arrSize);
cout << "enter " << arrSize << " values. Enter the values one after the other." << endl;
for (int i = 0; i < arrSize; i++)
{
ar.SetValue(i);
ar.GetValueOf(i);
}
cout << "enter the index to fetch the value" << endl;
cin >> arrIdx;
ar.GetValueOf(arrIdx);
}
else{
cout << "invalid input" << endl;
}
return 0;
}
程序 2:(正在运行的代码)
#include<iostream>
using namespace std;
// size is passed
class NewArray{
private:
int Size;
int *arrAddr;
public:
NewArray(int);
void GetValueOf(int);
};
NewArray::NewArray(int arSz){
int arr[arSz];
int idx;
Size = arSz;
arrAddr = arr;
cout << "An array of Size " << Size << " is created" << endl;
// Storing values in array
cout << "enter " << Size << " values. Enter the values one after the other." << endl;
for (int i = 0; i < Size; i++)
{
cin >> *(arrAddr+i);
}
// To get the value from the index
cout << "enter the index to fetch the value" << endl;
cin >> idx;
if ((idx >= Size) || (idx < 0))
{
cout << "index value is out of bound" << endl;
}
else
{
cout << "The value is " << *(arrAddr+idx) << endl;
}
}
int main()
{
int arrSize, arrIdx;
cout << "enter the size of array" << endl;
cin >> arrSize;
if (arrSize > 0)
{
NewArray ar(arrSize);
}
else{
cout << "invalid input" << endl;
}
return 0;
}
我已经尝试过这个特定示例,当数组大小为 10 并且我尝试写入第 7 个索引时,程序 1 崩溃。
谁能帮我找出原因?
【问题讨论】:
-
看看我编辑的答案...
标签: c++ arrays pointers constructor