Function that returns multiple elements

Asked

Viewed 36 times

0

I have a doubt in the following exercise:

Make a subroutine that takes a single value representing seconds. This subroutine should convert it to hours, minutes and seconds. All variables should be passed as a parameter, with no global variables.

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

int ConverterSegundos(int seg) {
    int hr, min, segundos, res[3];

    res[0] = hr = (seg / 60) / 60; //Calculo das horas
    res[1] = min = (seg / 60) % 60; //Calculo dos minutos
    res[2] = segundos = seg % 60; //Calculo dos segundos

    return res[0];
}

int main(int argc, char** argv) {
    int segundos,horario[3];

    printf("Digite os segundos: ");
    scanf("%d", &segundos);
    horario[0] = ConverterSegundos(segundos);

    printf("Conversão para o formato %d:mm:ss \n",horario[0]);

    return (EXIT_SUCCESS);
}

The problem comes at the time of returning the values, as are 3 values thought to store them in a vector with 3 positions and return it,good the problem that I am not able to do this. I don’t know how to print each position individually of the returned vector.

NOTE: I haven’t seen any pointers yet.

  • Technically the statement does not ask to return anything.

  • 1

    But finally, do not return a vector that has been declared within the function. If you don’t know how to handle pointers or allocate memory in the heap, it’s best to return nothing and print hours, minutes and seconds from within the subroutine. Incidentally, the concept of subroutine usually implies that it returns nothing (while "function" returns).

  • Got it, thank you very much friend, I’m going to print inside the subroutine itself msm

  • 1

    See also the response in the duplicate link I marked. There it explains how to "return" array (pass a pointer to array or allocate memory in hand).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.