Cprogramming 简明教程
Return array from function in C
在 C 中,函数可帮助程序员进行模块化程序设计。可以定义一个函数来接受一个或多个参数,它能够向调用环境返回单个值。但是,可以定义该函数来返回一个值数组。在 C 中,可以通过以下方法之一使函数返回一个数组:
Functions in C help the programmers to adapt modular program design. A function can be defined to accept one or more than one arguments, it is able to return a single value to the calling environment. However, the function can be defined to return an array of values. In C, a function can be made to return an array by one of following methods −
-
Passing the array as argument and returning the pointer
-
Declaring a static array in a function and returning its pointer
-
Using malloc() function
将数组嵌入一个结构变量中并将其传递给函数
Embedding the array inside a struct variable and passing it to a function
我们实现这些方法来计算给定数字的平方、立方和平方根。
We implement these methods to calculate the square, the cube and the square root of a given number.
Pass array by reference
在以下示例中,我们在 main() 中声明一个未初始化的数组并将其传递给 function ,以及一个整数。在该函数内,使用平方、立方和平方根填充该数组。该函数返回该数组的指针,然后使用该指针在 main() 函数中访问和打印这些值。
In the following example, we declare an uninitialized array in main() and pass it to a function, along with an integer. Inside the function, the array is filled with the square, cube and square root. The function returns the pointer of this array, using which the values are access and printed in main() function.
Example
#include <stdio.h>
#include <math.h>
int arrfunction(int, float *);
int main(){
int x=100;
float arr[3];
arrfunction(x, arr);
printf("Square of %d: %f\n", x, arr[0]);
printf("cube of %d: %f\n", x, arr[1]);
printf("Square root of %d: %f\n", x, arr[2]);
return 0;
}
int arrfunction(int x, float *arr){
arr[0]=pow(x,2);
arr[1]=pow(x, 3);
arr[2]=pow(x, 0.5);
}
Square of 100: 10000.000000
cube of 100: 1000000.000000
Square root of 100: 10.000000
Return static array
我们不必从 main() 中传递一个空数组,而是可以在被调用函数自身内声明一个数组,使用所需的值填充它,并返回它的 pointer 。但是,返回一个局部 variable 的指针是不可接受的,因为它指向一个不再存在的变量。请注意,局部变量在函数的作用域结束时即停止存在。因此,我们需要在被调用函数 (arrfunction) 内使用一个静态数组,并返回它的指针给 main()。
Instead of passing an empty array from main(), we can declare an array inside the called function itself, fill it with the required values, and return its pointer. However, returning a pointer of a local variable is not acceptable, as it points to a variable that no longer exists. Note that a local variable ceases to exist as soon as the scope of the function is over. Hence, we need to use a static array inside the called function (arrfunction) and return its pointer back to main().
Example
#include <stdio.h>
#include <math.h>
float * arrfunction(int);
int main(){
int x=100, i;
float *arr = arrfunction(x);
printf("Square of %d: %f\n", x, *arr);
printf("cube of %d: %f\n", x, arr[1]);
printf("Square root of %d: %f\n", x, arr[2]);
return 0;
}
float *arrfunction(int x){
static float arr[3];
arr[0]=pow(x,2);
arr[1]=pow(x, 3);
arr[2]=pow(x, 0.5);
return arr;
}
Square of 100: 10000.000000
cube of 100: 1000000.000000
Square root of 100: 10.000000
现在,考虑以下函数,它将生成 10 个随机数并使用一个数组返回它们,并按如下方式调用此函数:
Now, consider the following function which will generate 10 random numbers and return them using an array and call this function as follows −
Example
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/* function to generate and return random numbers */
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ ) {
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
当上述代码被编译并执行后,它会产生以下结果 -
When the above code is compiled together and executed, it produces the following result −
r[0] = 2110147662
r[1] = 1427553496
r[2] = 1243625529
r[3] = 857484361
r[4] = 513293736
r[5] = 964923407
r[6] = 36104419
r[7] = 1248464892
r[8] = 1838450240
r[9] = 2096489563
*(p + 0) : 2110147662
*(p + 1) : 1427553496
*(p + 2) : 1243625529
*(p + 3) : 857484361
*(p + 4) : 513293736
*(p + 5) : 964923407
*(p + 6) : 36104419
*(p + 7) : 1248464892
*(p + 8) : 1838450240
*(p + 9) : 2096489563
Using malloc() function
malloc() 函数可作为库函数在 stdlib.h header 文件中使用。它在程序的运行时动态分配一个内存块。正常变量声明会导致在编译时分配内存。
The malloc() function is available as a library function in stdlib.h header file. It dynamically allocates a block of memory during the runtime of a program. Normal declaration of variables causes the memory to be allocated at the compile time.
void *malloc(size_t size);
malloc() 函数返回一个通用空指针。要在分配的内存中分配某个数据类型的值,它必须被强制转换为所需类型。例如,要存储一个 int 数据,它必须强制转换为 int *,如下所示:
The malloc() function returns a generic void pointer. To assign values of a certain data type in the allocated memory, it must be typecast to the required type. For example, to store an int data, it must be typecast to int * as follows −
int *x = (int *)malloc(sizeof(int);
让我们分配一块足够存储一个数字的平方、立方和平方根的三个 float 类型值的内存块,并将 float 指针返回给 main(),在其中显示计算出的值。
Let us allocate a block of memory sufficient to store three float values corresponding to square, cube and square root of a number, and return the float pointer to main(), inside which the computed values are displayed.
Example
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
float * arrfunction(int);
int main(){
int x=16, i;
float *arr = arrfunction(x);
printf("Square of %d: %f\n", x, arr[0]);
printf("cube of %d: %f\n", x, arr[1]);
printf("Square root of %d: %f\n", x, arr[2]);
return 0;
}
float *arrfunction(int x){
float *arr = (float *)malloc(3*sizeof(float));
arr[0]=pow(x,2);
arr[1]=pow(x, 3);
arr[2]=pow(x, 0.5);
return arr;
}
Square of 16: 256.000000
cube of 16: 4096.000000
Square root of 16: 4.000000
Using array element in struct
使用此方法,我们将在其内部声明一个 struct ,其中有一个 float 数组作为其元素。被调用函数 (myfunction) 声明一个结构变量,用其收到的参数的平方、立方和平方根填充数组元素,并将其返回给 main() 函数。
In this method, we will declare a struct, inside which there is an float array as its element. The called function (myfunction) declares a struct variable, populates the array element with square, cube and the square root of the argument received by it, and returns it to the main() function.
Example
#include <stdio.h>
#include <math.h>
struct mystruct{
float arr[3];
};
struct mystruct myfunction(int x);
int main(){
int x = 9;
struct mystruct s = myfunction(x);
printf("Square of %d: %f\n", x, s.arr[0]);
printf("cube of %d: %f\n", x, s.arr[1]);
printf("Square root of %d: %f\n", x, s.arr[2]);
return 0;
}
struct mystruct myfunction(int x){
struct mystruct s1;
s1.arr[0]=pow(x,2);
s1.arr[1]=pow(x,3);
s1.arr[2]=pow(x, 0.5);
return s1;
}
Square of 9: 81.000000
cube of 9: 729.000000
Square root of 9: 3.000000
Return string from function
使用相同的方法,可以将一个字符串传递给函数并从函数返回一个字符串。 string in C 是一个 char 类型的数组。在以下示例中,我们用一个指针传递字符串,在函数内处理它,并将其返回给 main()。
Using the same approaches, you can pass and return a string to a function. A string in C is an array of char type. In the following example, we pass the string with a pointer, manipulate it inside the function, and return it back to main().
在被调用函数内,有一个局部字符串。返回之前,将已传递的字符串与局部字符串连接。
Inside the called function, there is a local string. The string passed is concatenated with the local string before returning.
Example
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * hellomsg(char *);
int main(){
char * name = "TutorialsPoint";
char *arr = hellomsg(name);
printf("%s\n", arr);
return 0;
}
char * hellomsg(char *x){
char *arr = (char *)malloc(50*sizeof(char));
strcpy(arr, "Hello ");
strcat(arr, x);
return arr;
}
Hello TutorialsPoint