Home > Software engineering >  The second parameter in a function is always 0
The second parameter in a function is always 0

Time:11-30

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?

CodePudding user response:

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.

  • Related