Pass data from a struct within the function

Asked

Viewed 1,363 times

3

I’m doing a college job where I have a separate function that gets two values (WEIGHT and HEIGHT) and returns the BMI.

I have tbm a struct called STUDENT where is stored weight and height and a vector of 20 positions that will store the structures.

The program has a menuzinho where in option 1 the user will register the weight and height, and in option 4 I have to show the Name, IMC and the condition according to a table that was passed to me. (The condition I know how to do)

I did almost the entire program but getting to the part of calculating the BMI I can’t pass struct within the function. I know there’s a way to pass for value or reference but I’ve tried and I can’t.

Could someone help me? I thank you in advance!

//DECLARANDO ESTRUTURA 
struct aluno {

    char nome[100];
    char email[100];
    float altura;
    float peso;
};

//VETOR 
struct aluno info[21];


//FUNÇÃO SEPARADA DE IMC
float calculaImc(float altura, peso) {


    float resultado;

    resultado = peso / (altura*altura);
    return resultado;
}

//FUNÇÃO PRICIPAL
int main() {

    setlocale(LC_ALL,"portuguese");

    //DECLARANDO OUTRAS VARIAVEIS NECESSARIAS
    int i, op, posicao, excluir;

    do{

        system("cls");
        printf("\nCADASTRANDO ALUNOS NA ACADEMIA\n");
        printf("\n\t MENU \n");
        printf("\n1. Cadastrar aluno.\n");
        printf("2. Listar alunos.\n");
        printf("3. Apagar aluno.\n");
        printf("4. Listar IMC de alunos.\n");
        printf("0. Sair.\n");

        printf("\nEscolha uma das opções do menu: ");
        scanf("%i", &op);
        printf("\n");

        switch(op) {

            case(1):

                printf("Posições que já possuem cadastro: ");
                for(i=0; i<21; i++) {
                    if (info[i].nome[0] == '\0'){ 
                        continue;                 
                    }
                    printf("%d " , i);
                }

                printf("\nEscolha de 1 a 20: ");
                scanf("%d", &posicao);
                i=posicao;

                if(posicao > 20){
                    printf("\nVocê digitou um valor invalido, tente novamente!\n");
                }else{

                    printf("\n Posição escolhida: %d. \n", i);
                    printf("\n");

                    printf("Nome : ");
                    fflush(stdin);
                    gets(info[i].nome);

                    printf("Email : ");
                    fflush(stdin);
                    gets(info[i].email);

                    printf("Altura (m): ");
                    scanf("%f", &info[i].altura);
                    fflush(stdin);

                    printf("Peso (kg): ");
                    scanf("%f", &info[i].peso);
                    fflush(stdin);

                    if(info[i].nome[0] == '\0') {
                        printf("\nErro. Você não colocou um Nome.\n");
                    }else{
                    printf("\nAluno cadastrado com sucesso!\n");
                    }
                }
                break;

            case(2):

                printf("Alunos cadastrados.\n");

                for(i=0; i<21 ; i++){
                    if (info[i].nome[0] == '\0'){
                        continue;
                    }
                    printf("\nAluno %d \n", i);
                    printf("Nome: %s \n" , info[i].nome);
                    printf("Email: %s \n" , info[i].email);
                    printf("Altura: %.2f m \n", info[i].altura);
                    printf("Peso: %.2f kg \n", info[i].peso);
                }

                break;

            case(3):

                printf("Apagar aluno: ");
                scanf("%d", &excluir);

                if(info[excluir].nome[0] != '\0') {
                    printf("\nEssa posição corresponde ao seguinte aluno: %s.\n", info[excluir].nome);

                break;

            case(4):
                for(i=0; i<21; i++) {
                    if (info[i].nome[0] == '\0'){ 
                        continue;               
                    }
                    printf("\nAluno %d \n", i);
                    printf("Nome: %s\n", info[i].nome);
                }

                break;
        }

    }while(op!=0);

   return 0;
}
  • Why do you need to pass the struct for the BMI function? You cannot only pass the weight and height and receive the result of the function in the main?

  • I think it could be tmb, but I did as Isac said and gave it right. Thanks msm so!

1 answer

4


The most normal would be to pass a pointer to the structure you want to access in the function, and in many cases it will be more efficient because it avoids copying content unnecessarily.

The function would look like this:

//FUNÇÃO SEPARADA QUE RECEBE PESO E ALTURA E RETORNA O IMC
float calculaImc(struct aluno *al) {
//                            ^--- Tipo ponteiro para struct aluno
    float resultado;

    resultado = al->peso / (al->altura * al->altura);
    //            ^-----------^------------^-- acede com ponteiro -> campo
    return resultado;
}

And the call to function of main would be:

calculaImc(&info[i]);

Notice I put &info[i], for the & access the position in the memory of the element. This is necessary because the function receives a pointer, ie the memory location where the structure is.

Fitting into your case 4 would be:

case(4):
    for(i=0; i<21; i++) {
        if (info[i].nome[0] == '\0'){ //SE A PRIMEIRA POSIÇÃO DA STRING FOR IGUAL A \0
            continue;                 //ENTÃO PULA PARA O PROXIMO
        }
        printf("\nAluno %d \n", i);
        printf("Nome: %s\n", info[i].nome);
        printf("IMC: %f\n", calculaImc(&info[i])); //<--imc aqui com & para ser o ponteiro
    }

Recommendations:

  • Avoid using the function getch, because it is windows specific which makes your program less portable.
  • Do not mix gets with scanf. Better yet, don’t use gets at all, as it is a dangerous function and susceptible to attacks from buffer overflow. In addition to using the two creates problems of passages from one to another with what is left in the buffer input. This is what led you to use several fflush(stdin), not only are not ideal, but it is not even guaranteed that all implementations actually clean up buffers with that call.

Note:

In the function statement calculaImc that has in the question, was missing the type for the parameter peso:

float calculaImc(float altura, peso) {
//                            ^---- aqui
  • Thank you very much man, gave it right!!!!! Regarding these tips I will try to put into practice. I saw msm that it is better to use fgets but I was not able to implement in my code.

Browser other questions tagged

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