Problem in returning Struct in C

Asked

Viewed 152 times

0

I’m making a simple program in C that takes name, enrollment and two student grades but when returning the value typed struct in the function Show it does not return anything

#include <stdio.h>

#define N  2

typedef struct {
  char nome[30];
  int matricula;
  float nota1;
  float nota2;
} Aluno;

void Mostrar(Aluno a) {
  printf("%s\n","teste");
  printf("nome = %s\n",a.nome);
  printf("matricula = %d\n",a.matricula);
  printf("nota = %f\n",a.nota1);
  printf("nota2 = %f\n",a.nota2);
}

int main() {
  Aluno a;
  Aluno alunos[N];
  int i;

  for (i = 0; i < N; i++) {

    printf("Digite o nome do aluno");
    fflush(stdin);
    gets(alunos[i].nome);

    printf("Digite a matricula do aluno");
    scanf("%d", &alunos[i].matricula);

    printf("Digite a nota 1 do aluno");
    scanf("%f", &alunos[i].nota1);

    printf("Digite a nota 2 do aluno");
    scanf("%f", &alunos[i].nota2);
  }

  Mostrar(alunos[N]);

  return 0;
}

1 answer

1

One thing don’t use the function gets, gets is evil. Prefer scanf.

Another thing you stated alunos as a two-element vector, alunos[0] and alunos[1]. Only in your code you were trying to display alunos[N] which is the same as alunos[2] that doesn’t exist.

What I did was change the gets for scanf and show the value of alunos[0] and alunos[1].

    int main() {
        Aluno a;
        Aluno alunos[N];
        int i;

        for(i=0;i < N; i++) {
            printf("Digite o nome do aluno");

            // Modifiquei aqui.
            scanf("%s",&alunos[i].nome);

            printf("Digite a matricula do aluno");
            scanf("%d",&alunos[i].matricula);

            printf("Digite a nota 1 do aluno");
            scanf("%f", &alunos[i].nota1);

            printf("Digite a nota 2 do aluno");
            scanf("%f",&alunos[i].nota2);

        }

        // Modifiquei aqui.
        Mostrar(alunos[0]);
        Mostrar(alunos[1]);

        //Ou então pode usar essa sintaxe. Para usar comente as duas utimas linhas e descomente a próxima linha.
        //for(int i=0; i < N; i++) { Mostrar(alunos[i]);}

        return 0;
    }
  • 1

    True, thank you very much, but if my vector was size 10, would I have to write 10 times the students[0], students[1] and so on? Or is there another way to get all vector positions? Because I tried students[N] and couldn’t get

  • Use a for loop: for(int i=0; i < N; i++) { Mostrar(alunos[i]);}

  • 1

    the normal in case of passing a structure to a function is to use the passage by reference; thus the declaration of the "Show" function would be Mostrar(Aluno*), and the call would be Mostrar(&alunos[0]), or Mostrar(&alunos[i]), etc.

  • @zentrunix: Yes. If you want to edit the answer, feel free.

Browser other questions tagged

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