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
  #6
May 11th, 2004
Hi Dave,
I appreciate for your help, but it does not work correctly in the following case. We declare static local variable, so this variable will stay until the program is terminated. Hence, although we want to have 2 different arrays, the first one is modified because 2 pointers in main() actually point in the same memory location. Would you show me another way to do it? By the way, in the first version, I mistyped LENGHT, sorry for that.

#include <iostream>
#define LENGTH 5

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

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

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

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

int* array2 = getArray();

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

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

return 0;
}

int* getArray()
{
int static array[LENGTH];

for (int i = 0; i < LENGTH; i++)
{
cout << "Enter an integer: ";
cin >> array[i];
}

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

return array;
}

void printArray(int* array)
{
for (int i = 0; i < LENGTH; i++)
cout << *(array+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
10 20 30 40 50

Press any key to continue

*/
Reply With Quote