In my code, I am trying to create a dynamic array with initArray function, and in main I would like to use this initialized array. However, whenever i called the initialized array in main, it is giving me an error.
Here is what i tried:
void main()
{
int *a = NULL;
int n;
cout<<"Enter size:";
cin>>n;
initArray(a,n);
for(int j=0;j<n;j++)
{
cout<<a[j]<<endl;//Crashes here
}
}
void initArray(int *A, int size)
{
srand((unsigned)time(0));
A = new int[size];
for(int i=0;i<size;i++)
{
A[i] = rand()%10;
}
}
When i do initArray part in main, it works. What am i doing wrong?
I see two problems:
the function accepts a pointer. When you write
A = ...you’re only changing the copy of the pointer that gets passed to you by value. You could usevoid initArray(int* &A, int size)instead, or have the function return a pointer.if that’s the full code, you might need a forward declaration of the
initArrayfunction.