English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++It will not return the entire array, but it can return a pointer to the array. Outside the function, the address of a local variable cannot be returned. By making the local variable static, it can return the address of the local variable.
The following is the syntax for returning a pointer.
int * function_name() { body }
Here,
function_name-User-provided function name.
The following is an example of returning an array from a function.
#include <iostream> using namespace std; int * ret() { static int x[3]; for(int i=0 ; i<5 ; i++) { cout << " " << &x[i]; } return x; } int main() { ret(); return 0; }
Output result
0x601180 0x601184 0x601188 0x60118c 0x601190
In the above program,ret()
Created a function and returned an array. Declare a static int type array and print the address of the allocated memory block.
int * ret() { static int x[3]; for(int i=0 ; i<5 ; i++) { cout << " " << &x[i]; } return x; }
inmain()
in the function, which functionret()
is called-
ret();