简体   繁体   中英

C - Getting a segmentation fault(core dumped) error in this simple program

This is a simple program, that finds teh smallest and largest element of a 10-array. I'm not sure why I'm getting the segmentation fault(core dumped) error.

#include <stdio.h>

int main(void) {
    int i, j, min, array[10], max, n;

    //This loop get user input for the elements of the array
    for(i = 0; i < 10; i++) {                   
        printf("Enter element number %d:", i);
        scanf("%d", &n);
        array[i] = n;
    }

    min = array[0];
    max = array[0];

    //This loop finds the smallest element of the array
    for(j = 0; j < 10; j++) {
        if(min > array[j]) {
            min = array[j];
        }
    }

    //This loop finds the largest element of the array
    for(j = 9; j >= 0; j++) {
        if(max < array[j]) {
            max = array[j];
        }
    }

    printf("smallest value is: %d", min);
    printf("largest value is: %d", max);

    return 0;
}
for(j = 9; j >= 0; j++)

should be

for(j = 9; j >= 0; j--)

if you want to iterate from the last to the first. You access array[10] in the second iteration, which is out of bounds.

Also there is no reason to iterate from the last to the first, so

for(j = 0; j < 10; j++)

would also work.

You can do the whole job in a single for loop (reading from stdin, look if it is larger than the max/smaller than the min) and so you do not need the array.

for (j = 9; j >= 0; j++)

Here you start from 9 and do j++!

do this:

for (j = 9; j >= 0; j--)

By the way you can do this

scanf("%d", array + i);

The loop below tries to point to a location that is beyond the assigned memory space.

for(j = 9; j >= 0; j++) 

Instead try writing:

for(j=9; j >= 0; j--) 

You may go for, an incrementing loop, as suggested by @mch, if you you'd like. Also, as a suggestion, skip using the variable j here. You can use i instead. Won't be any issues, since you are assigning 0 to it in loop. You'd be saving 4 precious bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM