Ivo Görner
Ivo Görner

Reputation: 13

Segmentation fault when accessing dynamically allocated array in a function

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;

}

Upvotes: 1

Views: 728

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

scanf("%d",array[i]);

Since array is an int**, array[i] is an int* (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.

Upvotes: 2

Related Questions