Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - In C language, how does the return statement return an array?
In C language, how does the return statement return an array?
First of all, C/C++ can only return pointers to arrays, but not the whole array. Even if a pointer to an array is returned, it will be dangerous if the array in the function is automatic. This is a more realistic expression. If you really need to return all the element values of the automatic array from the function, is there any way? Yes Because C/C++ is allowed to return structures, you can define a structure template, arrange arrays as members in it, temporarily declare structure variables in the function, and operate the arrays in it; After the completion, the structure variable is returned, and the return of the array can be indirectly realized by receiving the same type of structure variable in the main function. The sample code is as follows:

# Contains? " stdio.h "

struct? A {

int? m[30]; //Arranges the array m in the structure a..

};

struct? Answer? Fun (int? n){

int? I,j,k;

struct? Answer? s; //Declare the automatic structure variable s in the function.

for(I = 0; I & ltn;; s . m[i++]= I+ 1); //Assign 1~ 15 to the structure member array m.

for(j=n- 1,I = 0; I & ltj;; I++, j-)// Invert this array.

k=s.m[i],s.m[i]=s.m[j],s . m[j]= k;

Return? s; //returns the structural variable s

}

int? main(int? argc,char? *argv[]){

Answer? a; //The structural variable A of the same type declared in the main tone function receives the return value of the function fun.

int? Me;

A = fun (15); //Call fun with 15 (not more than 30, just for example) and assign the result to A..

for(I = 0; I< 15; I++)// output to see if it is in reverse order. ...

printf("%d?" ,a . m[I]);

printf(" \ n ");

Return? 0;

} The running results are as follows: