我正在使用一個int指針作爲私人訪問數組。當我爲存儲編寫單獨的函數並獲取數組的值時,程序崩潰。但是,如果我在構造函數中編寫get值和存儲值代碼,程序工作正常。我無法找到問題所在。使用指針作爲私人類訪問C++中的數組
計劃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;
}
我已經嘗試了這個特殊的例子,程序1在數組大小爲10時崩潰,以及當我試圖寫入第7個索引時。
任何人都可以請幫我找出原因嗎?
看看我編輯的答案... – 2015-04-02 07:57:05