Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ functions returning arrays

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.

like image 491
charmoniumQ Avatar asked Jul 15 '26 01:07

charmoniumQ


2 Answers

The problem is that you cannot return local arrays:

int a[] = {1, 2, 3};
...
return a;

is invalid. You need to copy a into dynamic memory before returning it. Currently, since a is allocated in the automatic storage, the memory for your array gets reclaimed as soon as the function returns, rendering the returned value invalid. Java does not have the same issue because all objects, including arrays, are allocated in the dynamic storage.

Better yet, you should avoid using arrays in favor of C++ classes that are designed to replace them. In this case, using a std::vector<int> would be a better choice.

like image 190
Sergey Kalinichenko Avatar answered Jul 17 '26 15:07

Sergey Kalinichenko


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.

#include <vector>

std::vector<int> getArray() 
{
    std::vector<int> a = {1, 2, 3};
    return a;
}
like image 22
Yuushi Avatar answered Jul 17 '26 16:07

Yuushi