0

Basically, I need to get the sum or the average of an entire line of a two-dimensional array.

First I need to get the line I need to use, then 'S' for sum or 'M' for average (Média in portuguese). Afterwards I need to read the entire array and finally I just have to do the requested action.

double soma_linha_matriz(double matriz[LINHA][COLUNA], int l)
{
    int i;
    double soma;
    
    soma = 0;
    
    for(i = 0; i < COLUNA; i++)
    {
        soma = soma + matriz[l][i];
    }
    
    return soma;
}

For some reason 'l' is always zero in here even though I made an scanf in the main function:


int main()
{
    double matriz[LINHA][COLUNA], resultado;
    
    int i, j, l;
    
    char sm;
    
    scanf("%d", &l);
    
    scanf("%s", &sm);
    
    for(i = 0; i < LINHA; i++)
    {
        for(j = 0; j < COLUNA; j++)
        {
            scanf("%lf", &matriz[i][j]);
        }
    }
    
    if(sm == 'S')
    {
        resultado = soma_linha_matriz(matriz, l);
        
        printf("%.1lf", resultado);
    }
    else if(sm == 'M')
    {
        resultado = media_linha_matriz(matriz, l);
        
        printf("%.1lf", resultado);
    }
    
    return 0;
}

I tried for a long time to correct it, but I don't exactly know why is this happening...

Could anyone help?

Lonrukas
  • 3
  • 2
  • What language is this? Could you please add the appropriate tag? – Phil Nov 30 '21 at 04:43
  • @Phil It is C. Sorry, I am new here, I thought I'd choose the language elsewhere. – Lonrukas Nov 30 '21 at 04:47
  • 1
    `scanf("%s", &sm);` This is undefined behavior, `"%c"` is the format specifier for a `char`, `"%s"` is for strings. – yano Nov 30 '21 at 04:48
  • @yano For some reason doing that results in the program closing immediately. That's why I used "%s" – Lonrukas Nov 30 '21 at 04:52
  • When you `scanf("%d", &l);` a newline is left in the input buffer, which is subsequently gobbled up by `scanf("%c", &sm);`, saving the newline to `sm`. You can prepend `"%c"` with a space to skip the newline: `scanf(" %c", &sm);`. See [here](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) for more info. – yano Nov 30 '21 at 05:02
  • @yano yeah, I only saw that now, thanks. – Lonrukas Nov 30 '21 at 05:06

1 Answers1

2

scanf("%s", &sm) reads a string, not a char. According to documentation it always stores a null terminator (Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters) - https://en.cppreference.com/w/c/io/fscanf) and it stores it to your 'l' variable.

Also this situation is a classical stack overrun error.

Sergey Miryanov
  • 1,820
  • 16
  • 29
  • When I use "%c" the program crashes as soon as I give a character. I did try putting a space before it and it works now, although I don't really know why besides something about the enter. But thanks, it helped a lot. – Lonrukas Nov 30 '21 at 05:01