C++ correct way to return pointer to array from function

前端 未结 7 981
慢半拍i
慢半拍i 2020-11-27 13:27

I am fairly new to C++ and have been avoiding pointers. From what I\'ve read online I cannot return an array but I can return a pointer to it. I made a small code to test it

7条回答
  •  日久生厌
    2020-11-27 14:13

    A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:

    #include 
    
    int main() {
      int a[] = {1, 2, 3, 4, 5}; 
    
      int* pArr = a;
      int* pFirstElem = &(a[0]);
    
      assert(a == pArr);
      assert(a == pFirstElem);
    
      return 0;
    }
    

    This also means that passing an array to a function should be done via pointer (and not via int in[5]), and possibly along with the length of the array:

    int* test(int* in, int len) {
        int* out = in;
        return out;
    }
    

    That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:

    #include 
    
    using namespace std;
    
    int main() {
      int* pArr = 0;
      {
        int a[] = {1, 2, 3, 4, 5};
        pArr = a; // or test(a) if you wish
      }
      // a[] went out of scope here, but pArr holds a pointer to it
    
      // all bets are off, this can output "1", output 1st chapter
      // of "Romeo and Juliet", crash the program or destroy the
      // universe
      cout << pArr[0] << endl; // WRONG!
    
      return 0;
    }
    

    So if you don't feel competent enough, just use std::vector.

    [answer to the updated question]

    The correct way to write your test function is either this:

    void test(int* a, int* b, int* c, int len) {
      for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
    }
    ...
    int main() {
       int a[5] = {...}, b[5] = {...}, c[5] = {};
       test(a, b, c, 5);
       // c now holds the result
    }
    

    Or this (using std::vector):

    #include 
    
    vector test(const vector& a, const vector& b) {
      vector result(a.size());
      for (int i = 0; i < a.size(); ++i) {
        result[i] = a[i] + b[i];
      }
      return result; // copy will be elided
    }
    

提交回复
热议问题