C++ functions returning arrays

后端 未结 3 1841
梦谈多话
梦谈多话 2021-01-14 23:55

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 Ar

相关标签:
3条回答
  • 2021-01-15 00:25

    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;
    }
    
    0 讨论(0)
  • 2021-01-15 00:34

    There are two places in memory that variables can go: the stack and the heap. The stack contains local variables created in methods. The heap holds other variables upon other conditions, like static variables.

    When you create a in GetArray() that was a local variable stored on the stack and a was a pointer to that location. When the method returned the pointer, that layer of the stack was released (including the actual values that the pointer was pointing to).

    Instead, you need to dynamically allocate the array, then the values will be in the heap which is not cleared when a function returns and a will point to them there.

    int * GetArray() {
      int* a = new int[3];
      a[0] = 1;
      a[1] = 2;
      a[2] = 3;
      cout << endl << "Verifying 1" << endl;
      for (int ctr = 0; ctr < 3; ctr++)
        cout << a[ctr] << endl;
      return a;
    }
    

    Now you're passing around the address of those ints to and from functions while the values all sit in the heap where they aren't released until the end of the program or (preferably) you delete them.

    0 讨论(0)
  • 2021-01-15 00:35

    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.

    0 讨论(0)
提交回复
热议问题