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);
}
Aucun commentaire:
Enregistrer un commentaire