Y
Y
Yan Nesterov2018-11-25 14:22:11
C++ / C#
Yan Nesterov, 2018-11-25 14:22:11

Why does the "Segmentation fault (core dumped)" error occur when compiling C code?

The task itself for which the code was written looks like this:
Given three arrays x[5], y[10], z [15]. For each
array, it is required to determine the number of
array elements belonging to the interval [a;b]. The
interval ends are defined by the user. If
the number is even, assign the value a to the first element
of the array, otherwise,
assign the value b to the last element of the array.
The program code must contain three
user-defined functions that provide:
1. Input of array elements;
2. calculation of the number of array elements
belonging to the interval [a;b];
3. replacement of the first or last element of the array.
My code:

#include <stdio.h>
#include <stdlib.h>
void arrFilling(int arr[],int arrSize){
    int min = 1;
    int max = 10;
    for(int n = 0; n < arrSize; n++){
        arr[n] = (rand() % (max - min + 1)) + min; 
        printf("%d ",arr[n]);
    }
}

int arrInterval(int arr[], int arrSize, int start, int end){
    int a = 0;   
    for(int n = 0; n < arrSize; n++){
        if(arr[n] >= start && arr[n] <= end ){
            a++;
        }
    }
    return a;
}

void arrReplace(int arr[],int arrSize,int ans){
    if(ans%2==1){
        arr[arrSize-1] = ans;
    }
    else{
        arr[0] = ans;
    }
}


int main()
{
    int x[5], y[10], z[15];
    int start, end;
    
    printf("Введите промежуток\n");
    printf("а - начало интервала: "); scanf("%d",&start);
    printf("b - конец иинтервала: "); scanf("%d",&end);
   
    arrFilling(x,5);
    printf("\n");
    arrFilling(y,10);
    printf("\n");
    arrFilling(z,15);
    printf("\n");
    
    int ans1 = arrInterval(x[5],5,start,end);
    printf("%d",ans1);
    int ans2 = arrInterval(y[10],10,start,end);
    printf("%d",ans2);
    int ans3 = arrInterval(z[15],15,start,end);
    printf("%d",ans3);
    
    arrReplace(x[5],5,ans1);
    arrReplace(y[10],10,ans2);
    arrReplace(z[15],15,ans3);
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-11-25
@muridse

arrInterval и arrReplace ожидают указатель, а получают int, первым параметром и т.д.
а z[15] (и остальное подобное) это вообще за пределами массива.

Передавайте в них просто имя массива (оно же является указателем на первый элемент).
int ans1 = arrInterval(x,5,start,end);
    printf("%d",ans1);
    int ans2 = arrInterval(y,10,start,end);
    printf("%d",ans2);
    int ans3 = arrInterval(z,15,start,end);
    printf("%d",ans3);
    
    arrReplace(x,5,ans1);
    arrReplace(y,10,ans2);
    arrReplace(z,15,ans3);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question