0

I am trying to define the size of *arr and allocate memory for it inside the function init_array. But it leads to segmentation fault. What am I doing wrong? How do I achieve this result?

#include<iostream>

using namespace std;
int init_array(int* arr)
{
    int n;
    cout<<"Number of elements? ";
    cin>>n;
    arr = new int[n];
    for(int j=0; j!= n; j++)
        arr[j] = j*j;
    return n;
}

int main()
{
    int *arr=nullptr;
    int n;
    n = init_array(arr);
    for(int i=0; i!=n; i++)
        cout<<*(arr+i);
}
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Sriram
  • 99
  • 5
  • Possible duplicate of [What is a segmentation fault?](https://stackoverflow.com/questions/2346806/what-is-a-segmentation-fault) – FilipRistic Jul 24 '18 at 20:14
  • do you really have to manipulate memory? There are safer ways to achieve your desired functionality. – Red.Wave Jul 25 '18 at 07:30
  • @Red.Wave - In my project arr is a huge object. So the fewer times I copy it or move it, the better it is. Also, I want to call the function init_array() a few times. I do not just want to `return arr`, because there are multiple huge objects that are simultaneously manipulated in there. So, I am little unsure on how to achieve it. Any help would be great! Thanks – Sriram Jul 25 '18 at 16:11
  • @Sriram is that about a dynamic array or not? We need more clarification please. there are multiple known approaches for typicall cases. – Red.Wave Jul 25 '18 at 16:26
  • This is about a dynamic array (I suppose). I do not know `n` before I actually call the function `init_array`. – Sriram Jul 25 '18 at 17:59

1 Answers1

2

The parameter arr is being passed by value, so assigning to it in the init_array() function doesn't update the variable in main(). You need to make it a reference parameter:

int init_array(int* &arr)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    what about delete[]. do you wanna leave it leakin memory? where did the return statement go? – Red.Wave Jul 25 '18 at 01:29
  • @Red.Wave The caller takes responsibility for deleting the object when it's done with it. The rest of the function doesn't change, so I didn't show it. – Barmar Jul 25 '18 at 06:39
  • but IMHO the OP needs to learn it; I strongly guess he doesn't know. – Red.Wave Jul 25 '18 at 06:42
  • Maybe, but that's independent of how he passes the variables around when creating the object. – Barmar Jul 25 '18 at 06:44
  • I did use what @Barmar suggested. And I deleted the object after calling it. Let me share the actual code where I am using it, if that could help. (https://github.com/ssriram1992/BalasUnionOfPolyhedra/blob/master/BalasPolyhedron.cpp Calling in line 75 and deleting between line 95 and 100) – Sriram Jul 25 '18 at 17:58