返回数组时出现分段错误 [英] Segmentation fault when returning an array

查看:73
本文介绍了返回数组时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解决此代码.我们必须返回一个数组作为函数的输出.我必须编码的函数是这样给出的.

I was trying to solve this code. We have to return an array as an output to the function. The function in which I have to code is given like this.

 int *findTwoElement(int *arr, int n) {
        // code here
    }

当我声明我的 ans 数组并返回它时,我收到了 segmentation fault

When I am declaring my ans array, like given below form and returning it, I am getting a segmentation fault

int ans[2];
ans[0]=b;
ans[1]=a;
        
return ans; 

但是当我声明我的 ans 数组时,就像下面给出的表单并返回它一样,它工作正常

But when I am declaring my ans array, like given below form and returning it, it is working fine

int *ans=new int(2);
   
ans[0]=b;
ans[1]=a;
    
return ans;

编辑-->那么,如果第一个代码返回 segmentation fault,此代码(如下所示)如何正常工作?

EDIT--> Then how come this code (given below) is working correctly if the first code is returning segmentation fault?

#include <iostream>
using namespace std;
 
int* fun()
{
    int arr[100];
 
    /* Some operations on arr[] */
    arr[0] = 10;
    arr[1] = 20;
 
    return arr;
}
 
int main()
{
    int* ptr = fun();
    cout << ptr[0] << " " << ptr[1];
    return 0;
}

我不明白我做错了什么.任何帮助将不胜感激.谢谢你.:)

I am not getting what I am doing wrong. Any help will be appreciated. Thank you. :)

推荐答案

如果在函数内部声明了 int ans[2];,则它是一个具有自动存储持续时间 并且它的生命在从函数返回时结束,所以你不能在返回后使用指向它的指针.

If int ans[2]; is declared inside functions, it is an array having automatic storage duration and its life ends when returning from the function, so you must not use pointers to that after returning.

还要注意 int *ans=new int(2); 不是分配一个 2 元素的数组,而是分配带有初始值 2 的单个 int.分配一个数组应该是int *ans=new int[2];.

Also note that int *ans=new int(2); is not allocating a 2-element array but allocating single int with the initial value 2. It should be int *ans=new int[2]; to allocate an array.

这篇关于返回数组时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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