Sriram
Sriram

Reputation: 99

new operator in a function C++

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);
}

Upvotes: 0

Views: 36

Answers (1)

Barmar
Barmar

Reputation: 781004

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)

Upvotes: 2

Related Questions