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

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

    you can (sort of) return an array

    instead of

    int m1[5] = {1, 2, 3, 4, 5};
    int m2[5] = {6, 7, 8, 9, 10};
    int* m3 = test(m1, m2);
    

    write

    struct mystruct
    {
      int arr[5];
    };
    
    
    int m1[5] = {1, 2, 3, 4, 5};
    int m2[5] = {6, 7, 8, 9, 10};
    mystruct m3 = test(m1,m2);
    

    where test looks like

    struct mystruct test(int m1[5], int m2[5])
    {
      struct mystruct s;
      for (int i = 0; i < 5; ++i ) s.arr[i]=m1[i]+m2[i];
      return s;
    }
    

    not very efficient since one is copying it delivers a copy of the array

提交回复
热议问题