Peter Dowling
Peter Dowling

Reputation: 11

C programing: Segmentation fault when reading numbers into a array

I am baffled and looking for some help on what seems so simple. I am trying to set the size of an array in my main then call my function to have a user input the numbers into a array of that size. After running the program I get the output:

Enter how many: (users length of array)
Enter data: (users first number)
Segmentation fault (core dumped)

I am wondering what I did wrong:

#include <stdio.h>
int main(void)
{
    int length, arr, size;

    printf("enter how many: ");
    scanf("%i", &length);

    readArray(arr, length);

    return 0;
}

int readArray(int arr[50], int length)
{
    int i, data;

    for (i =0; i < length; ++i)
    {
        printf("enter data %i: ", i);
        scanf("%i", data);
        arr[i] = data;
    }
    return 0;   
}

Thank you for your help in advance!

Upvotes: 0

Views: 84

Answers (2)

Baldrickk
Baldrickk

Reputation: 4409

Your readArray function declaration looks like this:

int readArray(int arr[50], int length)

That is, it takes and array of integers (arr) and an integer (length)

Your code in main however:

int length, arr, size;
//...
readArray(arr, length);

declares arr as an int.

To fix this, you need to declare arr as an array of size length:

printf( "enter how many: " );
scanf( "%i", &length );

int arr[length];  //declares an array 'arr' of size 'length'

Note that you also don't need to declare the size of the array in the readArray declaration.
Arrays in C are passed as pointers to the first element. Therefore, the declaration should be:

int readArray(int arr[], int length)

which is equivalent to:

int readArray(int *arr, int length)

Finally, you did it correctly in main but in your readArray function, remember the & in the scanf function call:

scanf( "%i", &data );

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311058

Change your code the following way

#include <stdio.h>

void readArray( int arr[], int length );

int main(void)
{
    int length;

    printf( "enter how many: " );
    scanf( "%i", &length );

    int arr[length];

    readArray( arr, length );

    return 0;
}

void readArray( int arr[], int length )
{
    int i, data;

    for ( i = 0; i < length; ++i )
    {
        printf( "enter data %i: ", i );
        scanf( "%i", &data );
        arr[i] = data;
    }
}

Upvotes: 2

Related Questions