C语言函数如何正确返回数组?

一个错误的例子

#include<stdio.h>
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]);
} 

程序运行结果
在这里插入图片描述
接着把注释掉的那段代码取消注释
程序运行结果
在这里插入图片描述
难道就因为加了一句话,就出错?可是我除了输出啥也没干啊!
实际上我们返回数组的方法是错误的,问题的根源在于:我们在function函数中,定义局部变量a,返回的是a的地址,而a是一个局部变量,当函数调用结束时,局部变量中数据可能已经不复存在了。

方法一:函数外初始化数组

#include<stdio.h>
int* function(int* a){
    
    
	a[0] = 1;
	a[1] = 2;
	a[2] = 3;
	return a;
}
int main(){
    
    
	int a[10];
	int* b;
	b = function(a);
	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<stdio.h>
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<stdio.h>
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]);
} 

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/q54188p/article/details/113355998