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; }
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; }
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).
std::tr1::array
boost::array
a1 - , . int *, .
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(), / .
. arr - , int *sum(int, int) . SO, , , , arr , .
arr
int *sum(int, int)
main(), / .
main()
- sum() main(), .
sum()
, , , std::vector std::pair:
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; }
. int arr[2]; . . .
int arr[2];
.. , arr - , .
. a1 , , . .
" ", new, . , , .
new
arr - sum(), . , , a1.
arr, . - . , arr , .
Source: https://habr.com/ru/post/1741296/More articles:Color change in Windows Form - c #asp.net impersonates a user to access network resources - asp.netC # console application extension in a WPF application - c #How to call other constructors from a constructor in C #? - c #Любой способ переопределить, как элемент привязан xsd.exe - xsdHow to check the external interface of Asp.Net? - user-interfaceчто может привести к большому расхождению между младшим временем GC и общим временем паузы? - javaResize the image to 100% of the height of the div and keep the aspect ratio - jqueryPython: how to create a container with elements that should reference their container - pythonС#/. NET: укажите, существует ли сервер, Query DNS для записей SVC - c#All Articles