从C中的函数返回数组:Segmentation Fault [英] Returning an array from a function in C: Segmentation Fault

查看:92
本文介绍了从C中的函数返回数组:Segmentation Fault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用头文件实现一个简单的程序,其中头文件中的函数接受一个int数组并返回一个int数组.

I am trying to implement a simple program using a header file where a function in the header file accepts an int array and returns an int array too.

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的打印循环中出现分段错误.

I am getting a segmentation fault at the print loop in test.c.

推荐答案

您不能从函数返回数组.返回point()时,此函数内的本地数组超出范围.该数组在堆栈上创建,并且在函数完成返回后将被销毁.与之关联的所有内存都将被丢弃,并且返回的指针指向堆栈上不再存在的位置.您需要在堆上分配一个指针,然后返回该指针.这允许array在您的程序之间共享.

You cannot return arrays from functions. When point() returns, the local array within this function goes out of scope. This array is created on the stack, and will get destroyed once the function finishes returning. All memory associated with it is discarded, and the returned pointer points to a position on the stack that doesn't exist anymore. You need to instead allocate a pointer on the heap, and return that instead. This allows array to be shared across your program.

代替:

int array[4];

您需要使用 malloc() :

int *array = malloc(4 * sizeof(*array)); /* or sizeof(int) */
if (array == NULL) {
    /* handle exit */
}

malloc()在堆上分配请求的内存,并返回指向它的void*指针.

malloc() allocates requested memory on the heap, and returns a void* pointer to it.

注意::malloc()在失败时可以返回NULL,因此需要始终对其进行检查.您还需要 free() 以前由malloc()分配的任何内存.您还不需要强制返回malloc().

Note: malloc() can return NULL when unsuccessful, so it needs to be checked always. You also need to free() any memory previously allocated by malloc(). You also don't need to cast return of malloc().

要指出的另一件事是在整个程序中使用幻数4.确实应该使用sizeof(a)/sizeof(a[0])来计算.

Another thing to point out is using the magic number 4 all over your program. This should really be calculated using sizeof(a)/sizeof(a[0]).

您可以在main()中将其声明为size_t变量:

You can declare this as a size_t variable in your main():

size_t n = sizeof(a)/sizeof(a[0]);

或者您可以使用宏:

#define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0]))

只要您想要数组的大小,只需调用ARRAYSIZE(a).

And simply call ARRAYSIZE(a) everytime you want the size of the array.

这篇关于从C中的函数返回数组:Segmentation Fault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆