Doubt in a question of pointers in C

1

The question is this:

Construct a function that takes two integer values a and b , return (passing by reference) the quotient, div, and the remainder division, mod, from a to b . The function should return -1 if it is not possible to perform operations and 0 if it is possible. An algorithm to use such a function should be created by treating the function return.

I made the code like this, but I have no idea what I'm doing:

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

int div (int *a, int *b)
{
    int resultado, resto, aux;
    if (*b==0)
    {
        return -1;
    }
    else
    {
        resultado = (*a / *b);
        resto = (*a % *b);
        return 0;
    }
}
int main (void)
}

int a, b, *resto, *resultado, *aux;
printf ("Digite o valor do dividendo: ");
scanf ("%i", &a);
printf ("Digite o valor do divisor: ");
scanf("%i", &b);
div (&a, &b);
if (div == 0)
{
    printf ("O resultado da divisao eh: %i ", resultado);
    printf ("O resto da divisao eh: %i", resto);
}
else
{
    printf ("Nao eh possivel realizar uma divisao por 0");
}
return 0;
}
    
asked by anonymous 03.11.2017 / 22:35

1 answer

2
  

construct a function that returns 0 if it is possible to do the operation, -1 otherwise

Here you did well, it is not possible to divide when the denominator is 0.

To make this comparison, as the denominator is passed by reference, you must *var to dereference. In this case, I'm assuming that b is always the denominator and a as the numerator. So knowing if it's possible to split is to make the following comparison:

*b == 0
  

should return the quotient and the rest by reference

Here the mess begins ;-)

I, who like to work with memory to squeeze and only optimize when it encounters a bottleneck, would pass two additional parameters. The signature of the function would look like this:

int div(int *a, int *b, int *quociente, int *mod);

Thinking about this scheme, assigning quociente and mod would be done like this:

int va = *a; // guarda o valor de a para ficar mais limpa a manipulação 
int vb = *b; // idem para b

*quociente = va/vb;
*mod = va%vb;

But as I believe the intention would be to return on a and b the result of this operation, then you could not change the signature of the function:

int div(int *a, int *b);

To store division and module values without destroying the values pointed to by a and b , you would need to save a copy of these values. It would be so to receive the values via a and b and also return via a and b :

int va = *a; // guarda o valor de a para ficar mais limpa a manipulação 
int vb = *b; // idem para b

*a = va/vb;
*b = va%vb;

The rest of the code seems correct at first glance.

    
03.11.2017 / 23:05