Home > Back-end >  What is causing the segmentation fault in this code? Code is in C
What is causing the segmentation fault in this code? Code is in C

Time:09-10

I've been working in C lately and I've started working with arrays recently. Can you help me identify what's causing the issue here? I'm fairly certain the function inputArray is, but I cannot figure out why.

#include <stdio.h>

void inputArray(int array[], int size);

int main() {
    int arraySize;
    printf("Enter size of array: \n");
    scanf("%d", &arraySize);
    int myArray[arraySize];
    inputArray(myArray[arraySize], arraySize);

    return 0;
}


void inputArray(int array[], int size){
    int i;
    for (i=0; i<size; i  ){
        printf("Enter value for array: \n");
        scanf("%d", array[i]);
    }
}

CodePudding user response:

This call

inputArray(myArray[arraySize], arraySize);

is incorrect. The compiler shall issue a message that the passed first argument has no the type int *. You are passing a non-existent element of the array with the index arraySize.

You need to write

inputArray(myArray, arraySize);

Also you have to write

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

or

scanf("%d", array   i);

instead of

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

CodePudding user response:

You do not need to pass in myarray[arraysize] into your helper function. Just myarray

  • Related