C语言函数如何正确返回数组? | 您所在的位置:网站首页 › 怎么输出整个数组 › C语言函数如何正确返回数组? |
一个错误的例子
#include
int* function(){
int a[5];
a[0] = 1;
a[1] = 2;
a[2] = 3;
return a;
}
int main(){
int* b;
b = function();
// printf("123\n");
printf("第一次%d%d%d%d\n",b[0],b[1],b[2],b[3]);
printf("第二次%d%d%d%d\n",b[0],b[1],b[2],b[3]);
}
程序运行结果 为什么这样就可以了呢?事实上,我们先在主函数中声明了a,相当于已经分配了一块固定的内存,然后将其地址传入,经过一番操作,再将地址返回,a的内容依旧还是那块内存,不会像之前那样作为局部变量被撤回。 方法二:使用static数组静态数组的生命周期贯穿整个程序,所以我们可以在函数内部创建一个静态局部数组,操作后再返回,这种方式数组的长度必须是函数内确定的。 #include int* function(){ static int a[5]; a[0] = 1; a[1] = 2; a[2] = 3; return a; } int main(){ int* b; b = function(); printf("123\n"); printf("第一次%d%d%d%d\n",b[0],b[1],b[2],b[3]); printf("第二次%d%d%d%d\n",b[0],b[1],b[2],b[3]); } 方法三:将数组包裹在结构体中,返回结构体数组包裹在结构体里面,然后返回结构体的一个实例。 因为结构体成员使用的是深拷贝(deep copy),所以这个方法能够有效。 #include struct Witharray{ int a[5]; }; struct Witharray function(){ struct Witharray test1; test1.a[0] = 1; test1.a[1] = 2; test1.a[2] = 3; return test1; } int main(){ struct Witharray test1 = function(); printf("%d%d%d",test1.a[0],test1.a[1],test1.a[2]); } |
CopyRight 2018-2019 实验室设备网 版权所有 |