1

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;

}

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

@IvoGörner Since scanf wants a pointer to the location where you want the int saved, you need to use scanf("%d", &(*array[i])) (or the somewhat slightly operator dense scanf("%d", (*array)+i)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.