View Single Post
Join Date: May 2004
Posts: 15
Reputation: tlee is an unknown quantity at this point 
Solved Threads: 0
tlee tlee is offline Offline
Newbie Poster

Re: Return Array from C++

 
0
  #8
May 11th, 2004
Thanks Dave. However, would you mind if I have another question regarding to the same problem? While I was waiting for your solution, I developed one in below.
I know your code is much superior than mine. I am just confused that why the compiler issues the error when I try to delete the pointers. Could you give me the explanation please?

#include <iostream>
#define LENGTH 5

using std::cout;
using std::cin;
using std::endl;

class Array
{
public:
Array()
{
array = new int(LENGTH);
}

~Array()
{
delete[] array;
}

void setElement(int index, int value)
{
if ( index < 0 || index >= LENGTH )
cout << "INVALID INDEX" << endl;

array[index] = value;
}

int getElement(int index) const
{
if ( index < 0 || index >= LENGTH )
cout << "INVALID INDEX" << endl;

return array[index];
}
private:
int* array;

};

Array* getArray();
void printArray(Array* array);

int main()
{
Array* array = getArray();

cout << "array in main" << endl;
printArray(array);

Array* array2 = getArray();

cout << "array in main" << endl;
printArray(array2);

cout << "array in main" << endl;
printArray(array);

delete array;
delete array2;

return 0;
}

Array* getArray()
{
int value = 0;
Array* array = new Array();

for (int i = 0; i < LENGTH; i++)
{
cout << "Enter an integer: ";
cin >> value;
array->setElement(i, value);
}

cout << "array in getArray()" << endl;
printArray(array);

return array;
}

void printArray(Array* array)
{
for (int i = 0; i < LENGTH; i++)
cout << array->getElement(i) << " ";

cout << endl;
cout << endl;
}

/*
Output:

Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
array in getArray()
1 2 3 4 5

array in main
1 2 3 4 5

Enter an integer: 10
Enter an integer: 20
Enter an integer: 30
Enter an integer: 40
Enter an integer: 50
array in getArray()
10 20 30 40 50

array in main
10 20 30 40 50

array in main
1 2 3 4 5

Press any key to continue
*/
Reply With Quote