I am sort of new to C++. I am used to programming in Java. This particular problem is causing me great issues, because C++ is not acting like Java when it is dealing with Arrays. In C++, arrays are just pointers.
But why does this code:
#include <iostream>
#define SIZE 3
using namespace std;
void printArray(int*, int);
int * getArray();
int ctr = 0;
int main() {
int * array = getArray();
cout << endl << "Verifying 2" << endl;
for (ctr = 0; ctr < SIZE; ctr++)
cout << array[ctr] << endl;
printArray(array, SIZE);
return 0;
}
int * getArray() {
int a[] = {1, 2, 3};
cout << endl << "Verifying 1" << endl;
for (ctr = 0; ctr < SIZE; ctr++)
cout << a[ctr] << endl;
return a;
}
void printArray(int array[], int sizer) {
cout << endl << "Verifying 3" << endl;
int ctr = 0;
for (ctr = 0; ctr < sizer; ctr++) {
cout << array[ctr] << endl;
}
}
print out arbitrary values for verify 2 and verify 3. Perhaps this has something to do with the way arrays are really handled as pointers.
Because your array is stack allocated. Moving from Java to C++, you have to be very careful about the lifetime of objects. In Java, everything is heap allocated and is garbage collected when no references to it remain.
Here however, you define a stack allocated array a, which is destroyed when you exit the function getArray. This is one of the (many) reasons vectors are preferred to plain arrays – they handle allocation and deallocation for you.