c++return array code example

Example 1: return array from function c++

#include <iostream> 
using namespace std; 
  
int* fun() 
{ 
    int* arr = new int[100]; 
  
    /* Some operations on arr[] */
    arr[0] = 10; 
    arr[1] = 20; 
  
    return arr; 
} 
  
int main() 
{ 
    int* ptr = fun(); 
    cout << ptr[0] << " " << ptr[1]; 
    return 0; 
}

Example 2: cpp return array

int * fillarr(int arr[], int length){
   for (int i = 0; i < length; ++i){
      // arr[i] = ? // do what you want to do here
   }
   return arr;
}

// then where you want to use it.
int main(){
int arr[5];
int *arr2;

arr2 = fillarr(arr, 5);

}
// at this point, arr & arr2 are basically the same, just slightly
// different types.  You can cast arr to a (char*) and it'll be the same.

Tags:

Cpp Example