C语言函数返回数组
C程序中,函数是不能直接返回一个完整的数组的,我们指定数组名本质是一个指针常量,那么能不能通过返回指针的方式间接返回数组呐?答案是不完全可以,函数内变量是局部变量,返回局部变量的地址是不可以的,但是由于静态变量的作用域为全局所有可以返回静态变量。所以这里有两种方式从函数中活动数组:返回静态变量地址、以指针参数的形式获得数组。
下面两个函数的定义,fun1在函数内定义一个静态数组变量,然后返回该静态变量地址(数组名)得到返回数组;fun2中使用两个指针作为参数,其中in_arg为入参用于传入数组,out_arg为出参,用于活动数组结果,第三个参数指定数组长度避免索引数组时下标越界。
// 以静态变量的形式返回数组地址
int *fun1(int *arr,int len){
int static out[20];
for ( int i = 0; i < len; i++)
{
out[i]=2*arr[i];
}
return out;
}
// 用指针参数带回数组
void fun2(int *in_arg, int *out_arg,int len){
for (int i = 0; i < len; i++)
{
out_arg[i]=3*in_arg[i];
}
}两种方式中,由于静态数组定义必须由固定的大小,这限制了函数使用的自由性,所有用指针参数带回数组的方式更好一些。
在stackoverflow上也有关于函数返回数组的问题:Returning an array using C
Option 1:
dynamically allocate the memory inside of the function (caller responsible for deallocating ret)
char *foo(int count) {
char *ret = malloc(count);
if(!ret)
return NULL;
for(int i = 0; i < count; ++i)
ret[i] = i;
return ret;
}Call it like so:
int main() {
char *p = foo(10);
if(p) {
// do stuff with p
free(p);
}
return 0;
}Option 2:
fill a preallocated buffer provided by the caller (caller allocates buf and passes to the function)
void foo(char *buf, int count) {
for(int i = 0; i < count; ++i)
buf[i] = i;
}And call it like so:
int main() {
char arr[10] = {0};
foo(arr, 10);
// No need to deallocate because we allocated
// arr with automatic storage duration.
// If we had dynamically allocated it
// (i.e. malloc or some variant) then we
// would need to call free(arr)
}
评论已关闭