本文转自:https://blog.youkuaiyun.com/earbao/article/details/53401800
关于C语言函数返回一个数组
c语言中函数不能直接返回一个数组,但是可以用其他方式实现类似功能,不过需要注意:
1、该数组不能是返回函数的局部变量数组,因为局部变量数组在退出函数后会被释放。
可以是全局变量,静态局部变量,动态分配内存,以及从函数参数传过来的数组地址。
2、返回指针时,无法返回长度,所以需要其它方式传回数组长度,以下是几种常用的方法。
1) 约定固定长度;
2) 以函数参数返回数组长度;
3)将长度保存在全局变量中;
4)约定数组结束标记;
5)在数组中存储数组长度,如存在第一个元素中。
有些时候需要子函数将一个数组返回出来,通常是两种方法,一种是靠指针,另一种是结构体。
一、先来看依靠指针怎么做
-
#include <stdio.h>
-
char *test(char *tmp)
-
{
-
return tmp;
-
}
-
void main(void)
-
{
-
printf(
"%s",test(
"第一个测试例子\n"));
-
}
二、使用结构体作为返回值来传递数组
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
#ifdef _WIN32
-
//#include <Windows.h>
-
#include <vld.h>
-
#endif
-
-
//直接返回指针,但是无法返回长度
-
char *test(char *tmp)
-
{
-
return tmp;
-
}
-
-
//返回数组首地址
-
char *test2()
-
{
-
//char tmp[30]="第一个测试例子\n";//错误写法,写成这样编译时弹出警告,最后的结果也是乱码
-
char *tmp=
"test2 demo";
//写成这样可以用指针返回数组首地址
-
return tmp;
-
}
-
//使用静态全局变量
-
char *test3()
-
{
-
//静态全局变量,但不是线程安全的,在多线程环境中就危险了
-
static
char tmp[
30]=
"third demo test003";
-
return tmp;
-
}
-
-
//动态分配内存, 调用malloc在堆上分配内存,记得free
-
int* getArrays(int n)
-
{
-
//malloc数组建立在heap堆上,调用完函数还在,返回了那个堆上数组的首地址
-
int*
array = (
int *)
malloc(
sizeof(
int)*n);
-
int base=
100;
-
for(
int i=
0;i<n;i++)
-
{
-
array[i]=base+i;
//赋值
-
-
}
-
return
array;
-
}
-
void showArr(int* arr,int len)
-
{
-
for(
int i=
0;i<len;i++)
-
{
-
printf(
"%d ",arr[i]);
-
}
-
printf(
"\n");
-
}
-
//从函数参数传过来的数组地址
-
int getCharsArray(char* output,int len)
-
{
-
strncpy(output,
"123456789 from china!",len);
-
return
0;
-
}
-
//动态分配内存
-
char* getCharsArrayByPoint(int len)
-
{
-
//malloc数组建立在heap堆上,调用完函数还在,返回了那个堆上数组的首地址
-
char*
array = (
char *)
malloc(
sizeof(
char)*len+
1);
-
memset(
array,
0,
sizeof(
char)*len+
1);
-
strncpy(
array,
"getCharsArrayByPoint from china!",len);
-
return
array;
-
}
-
-
struct ArrayStruct
-
{
-
char buf[
1024];
-
};
//定义结构体时不要忘了分号
-
-
//使用结构体作为返回值来传递数组
-
struct ArrayStruct byStruct(char *tmp)
-
{
-
struct ArrayStruct arr;
-
strcpy(arr.buf,tmp);
-
return arr;
-
}
-
//关于C语言函数返回数组的问题
-
int main(int argc, char *argv[])
-
{
-
char* line=test(
"first test demo\n");
-
printf(
"%s",line);
-
-
char* line2=test2();
-
printf(
"%s\n",line2);
-
-
char* line3=test3();
-
printf(
"%s\n",line3);
-
-
char line4[
1024]={
0};
-
getCharsArray(line4,
sizeof(line4));
-
printf(
"%s\n",line4);
-
-
char *line5=getCharsArrayByPoint(
150);
-
printf(
"%s\n",line5);
-
free(line5);
-
-
struct ArrayStruct arrStruct;
-
arrStruct=byStruct(
"byStruct");
//用结构体作为返回值传递数组
-
printf(
"%s\n",arrStruct.buf);
-
-
#define arrLen 10
-
int* arr=getArrays(arrLen);
-
showArr(arr,arrLen);
-
free(arr);
//和malloc配对
-
return
0;
-
}
两点注意:
1、数组之间的赋值不要直接,即不要直接将数组A赋给数组B,而是要用strcpy(字符型数组)或者memcpy(非字符型数组)。
2、用结构体定义变量和函数时不要忘了结构体名。