I am trying to create a function that fills multiple arrays with data. The problem is, I get a segmentation fault whenever I try to put in more than 2 numbers. It works fine when I don’t use a double pointer.
#include <stdio.h>
#include <stdlib.h>
int readInput(int **array);
int main()
{
int *array;
readInput(&array);
free(array);
return 0;
}
int readInput(int **array)
{
int n,i;
printf("Enter n:\n");
scanf("%d",&n);
*array = (int*) malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",array[i]);
}
return 0;
}
Since array is an
int**,array[i]is anint*(ie index 0 is the pointer to the array you just allocated, the rest is random unallocated memory)(*array)[i]is probably more like what you’re looking for.