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

前端 未结 7 983
慢半拍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:08

    New answer to new question:

    You cannot return pointer to automatic variable (int c[5]) from the function. Automatic variable ends its lifetime with return enclosing block (function in this case) - so you are returning pointer to not existing array.

    Either make your variable dynamic:

    int* test (int a[5], int b[5]) {
        int* c = new int[5];
        for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
        return c;
    }
    

    Or change your implementation to use std::array:

    std::array test (const std::array& a, const std::array& b) 
    {
       std::array c;
       for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
       return c;
    }
    

    In case your compiler does not provide std::array you can replace it with simple struct containing an array:

    struct array_int_5 { 
       int data[5];
       int& operator [](int i) { return data[i]; } 
       int operator const [](int i) { return data[i]; } 
    };
    

    Old answer to old question:

    Your code is correct, and ... hmm, well, ... useless. Since arrays can be assigned to pointers without extra function (note that you are already using this in your function):

    int arr[5] = {1, 2, 3, 4, 5};
    //int* pArr = test(arr);
    int* pArr = arr;
    

    Morever signature of your function:

    int* test (int in[5])
    

    Is equivalent to:

    int* test (int* in)
    

    So you see it makes no sense.

    However this signature takes an array, not pointer:

    int* test (int (&in)[5])
    

提交回复
热议问题