Reputation: 11
I'm trying to allocate memory to an array using a function. I have passed pointer by reference(using double pointer). The code compiles but segmentation error is thrown during run time.
#include<stdio.h>
#include<stdlib.h>
//funct to read array
int read(int **v){
int n,ele;
printf("enter number of elements \n");
scanf("%d",&n);
//p=(int*)malloc(n*(sizeof(int));
*v= (int*)malloc(n * sizeof(int));
for(int i=0;i<n;i++)
{
//printf("enter %d th element \n",i);
scanf("%d",&ele);
*v[i]=ele;
}
return n;
}
void main()
{
int *p=NULL;
int sz=read(&p);
for(int i =0;i<5;i++)
{
printf("%d",p[i]);
}
}
Upvotes: 0
Views: 98
Reputation: 1413
Here is the error: *v[i]=ele;
. In this case, you've first subscripted array and then have dereferenced it.
https://en.cppreference.com/w/c/language/operator_precedence. Change it to (*v)[i]=ele;
and it will work.
UPD. Don't forget to free(p)
to avoid memory leaks.
Upvotes: 3