严格来说,无法从函数返回一个数组,但可以从函数返回一个指向任何数据结构的指针,包括一个指向数组的指针。
一种方式如下:
|
|
千万要注意:不能从函数中返回一个指向函数的局部变量的指针。
另一种方式如下:
#include
<stdio.h>
#include
<stdlib.h>
struct tag{
int array[20];
}x, y;
struct tag func(void);
int main(void)
{
int i;
x = func();
for(i
= 0; i
< 20; i++){
printf("%d/n", x.array[i]);
}
exit(0);
}
struct tag func()
{
int i;
for(i
= 0; i
< 20; i++){
y.array[i]
= i;
}
return y;
}
本文介绍两种在C语言中从函数返回数组的方法。第一种方法通过返回指向数组的指针实现,并需要注意内存分配与释放;第二种方法则通过结构体传递数组。这两种方案均可有效解决C语言中返回数组的问题。
974

被折叠的 条评论
为什么被折叠?



