我正在尝试使用头文件实现一个简单的程序,其中头文件中的函数接受 int
数组并返回 int
数组也是如此。
在 header.h
:
int* point(int a[]);
在 header.c
:
#include<stdio.h>
#include "header.h"
int* point(int a[])
{
printf("In the point function\n");
int array[4],i;
for(int i=0;i<4;i++)
{
printf("%dth Iteration\n",i);
array[i]=a[i];
}
return array;
}
在 test.c
:
#include<stdio.h>
#include "header.h"
void main()
{
int *array,i;
int a[]={1,2,3,4};
printf("calling point function\n");
array=point(a);
printf("Back in the main function\n");
for(i=0;i<4;i++)
{
//SEGMENTATION FAULT HERE
printf("%d\n",array[i]);
}
}
我在 test.c
中的打印循环中遇到段错误.
最佳答案
您不能从函数返回数组。当point()
返回时,该函数内的本地数组超出范围。该数组在堆栈上创建,一旦函数完成返回,该数组就会被销毁。与其关联的所有内存都将被丢弃,并且返回的指针指向堆栈上不再存在的位置。您需要在堆上分配一个指针,然后返回该指针。这允许array
在您的程序中共享。
而不是:
int array[4];
您需要使用 malloc()
动态分配指针:
int *array = malloc(4 * sizeof(*array)); /* or sizeof(int) */
if (array == NULL) {
/* handle exit */
}
malloc()
allocates requested memory on the heap, and returns avoid*
pointer to it.
注意: malloc()
不成功时会返回 NULL
,因此需要始终进行检查。您还需要free()
之前由 malloc()
分配的任何内存。你也don't need to cast return of malloc() .
另一件事需要指出的是在你的程序中使用神奇的数字4
。这确实应该使用 sizeof(a)/sizeof(a[0])
来计算。
您可以在 main()
中将其声明为 size_t
变量:
size_t n = sizeof(a)/sizeof(a[0]);
或者您可以使用宏:
#define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
每次您需要数组的大小时,只需调用 ARRAYSIZE(a)
即可。
关于c - 从 C 中的函数返回数组 : Segmentation Fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41928056/