Home > Software engineering >  Segmentation fault (core dumped) (very simple program)
Segmentation fault (core dumped) (very simple program)

Time:10-28

I'm having this problem writing a very basic program to learn arrays in C. The message appears when putting more than 2 in the array size. SO: Linux, Clear Linux OS 64 bits

#include <stdio.h>

int main (void) {
    int array[0], k=0, init;
    
    printf ("Insert amount of values\n");
    scanf ("%i", &init);

    for (k=1; k<=init; k  ) {
        printf ("Insert values:");
        scanf ("%i", &array[k]);
    }
    for (k=1; k<=init; k  ) {
        printf("%i,", array[k]);
    }

     return 0;
}
Insert amount of values
3
Insert values:4
Insert values:2
Insert values:3
Segmentation fault (core dumped)

Tried changing the data type of the array and the "%i" to "%d"

CodePudding user response:

You are initializing an array of size 1 with int array[0].

You have two options :

  1. You declare the array with the biggest expected size for exemple int array[10], but you will just report your problem and get segfault at the 11th value entered.

  2. You dynamically manage the size of your arrays with malloc function.

  • Related