The array is not returning correctly

I am trying to return a simple array, but I am not getting the correct result. I get the following

arr1[0] = 1 
arr1[1] = 32767

while the result should be

  arr1[0] = 1 
  arr1[1] = 15

Please offer.

int *sum(int a, int b){
  int arr[2];
  int *a1;
  int result = a+b;
  arr[0]= 1;
  arr[1]= result;
  a1 = arr;
  return a1;
}
int main(){  

  int *arr1 =  sum(5,10);
  cout<<"arr1[0] = "<<arr1[0]<<endl;
  cout<<"arr1[1] = "<<arr1[1]<<endl;

  return 0;

}
+3
source share
9 answers

Try it...


#include <vector>
#include <iostream>

std::vector<int> sum(int a, int b)
{ 
  std::vector<int> rv(2);
  rv[0]= 1; 
  rv[1]= a+b; 
  return rv; 
} 

int main()
{   
  std::vector<int> arr1 = sum(5,10); 
  std::cout << "arr1[0] = " << arr1[0] << std::endl; 
  std::cout << "arr1[1] = " << arr1[1] << std::endl; 

  return 0; 
} 

+7
source

You cannot return arrays. All you return is a pointer to a local object, which is destroyed when it goes out of scope when the function returns.

You can pass a pointer to an array, so the array will be modified by the function.

In addition, you can return a copy of the array if it is completed inside a struct / class, for example std::tr1::array(or boost::array).

+16
source

a1 - , . int *, .

int *arr = (int *)malloc(sizeof(int) * 2));

//CAUTION you need to de-allocate memory [read about free()]

:

. arr - , int *sum(int, int) . SO, , , , arr , .

main(), / .

+5

- sum() main(), .

, , , std::vector std::pair:

std::pair<int,int> f(int a, int b) {
    return std::make_pair(1, a+b);
}

int main() {
    std::pair<int,int> res = f(5,10);
    std::cout << res.first << ", " << res.second << std::endl;
}
+5

. int arr[2]; . . .

+1

.. , arr - , .

+1

. a1 , , . .

" ", new, . , , .

0

arr - sum(), . , , a1.

0

arr, . - . , arr , .

0
source

Source: https://habr.com/ru/post/1741296/


All Articles