Why do I get the Segmentation fault (core dumped) error message?

I have the following exercise:

Writes a program, called Media, that reads an indeterminate number of integers per command line and calculate the mean. For example: ./ Average 3 5 1 2

The average is: 2.75

In the case of detecting that the user has not entered a number, display an error on the screen and finish.

I have written a solution for it but running it gives me the error message Segmentation fault (core dumped) and I don't know what the reason is.

I use this Code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main (int argc, char *argv[])
{
    double media = 0;
    int es_digito;
    int aux;
    es_digito = isdigit(argv[1]);
    for (int i = 1; i < argc && es_digito != 0; ++i) {
        aux = atoi(argv[i]);
        media += aux;
    }
    if (es_digito == 0) {
        printf("Hubo error. Solo valen numeros\n");
    } else {
        media = media/(argc-1);
        printf("La media es: %lf\n",media);
    }
}
 3
Author: Comunidad, 2016-03-22

1 answers

es_digito = isdigit(argv[1]);

That line has two problems:

Asking directly for Argument 2 without knowing if it exists is risky and can cause your program to fail. You should control that.

The second error is that argv is a double pointer (char *argv[]), then argv[i] is a pointer of type char. If you want to check the character you have to add an asterisk to the Code: es_digito = isdigit(*argv[1]);

On the other hand, if you look, you will see that es_digito is only assigned a value once, then you are not checking if each parameter is numeric. You are only checking the first one and your code assumes that the rest will be valid because yes.

 3
Author: eferion, 2016-03-22 15:38:50