Error when trying to pass a struct by reference in C?

3

I'm having pointers and I'm trying to do the following exercise:

Consider a register of students enrolled in a course, with the following information for each student:

• Student name: up to 80 characters
• Registration number: represented by an integer value
• Notes obtained in three tests, P1, P2, P3: represented by real values

(a) Define a C structure, named student, that has the appropriate fields to store a student's information, as described above. (b) Write a function that receives as a parameter a pointer to a structure of the type defined in the previous item and print on the computer screen a line with the name of the student and another line with the average obtained in the three tests. This function should follow the following prototype:

void imprime (struct aluno* a);

It's just giving the code error:

'#include stdio.h'
'#include stdlib.h'

void imprime(struct aluno *a);

int main()
{
    struct aluno{
        char aluno[80];
        int mat;
        float p1,p2,p3;
    } joao;

    printf("Digite o nome do aluno: ");
    gets(joao.aluno);

    printf("Digite a matricula do aluno: ");
    scanf("%i", &joao.mat);

    printf("Digite as notas do aluno:\n" );
    scanf("%d %d %d", &joao.p1,&joao.p2,&joao.p3);

    imprime(&joao);
    getchar();

    return 0;
}

void imprime(struct aluno* a){
    printf("%s",a->nome);
}

The error is as follows:

ERRO: |28|error: conflicting types for 'imprime'|
    
asked by anonymous 09.09.2014 / 22:37

2 answers

3

The first time the compiler finds the function imprime() it still has not found the definition of struct aluno .

Then, within the function main() , the struct aluno setting appears; which takes effect from then until the end of the program.

The second time that the imprime() function appears, the compiler has another idea of what struct aluno is.

That is, for the compiler there are two struct aluno different (with the same name) and it complains.

The best solution is to pass the definition of struct aluno to before any use; for immediately following% s of% s.

    
09.09.2014 / 23:07
0

Looking at your code, I suggest:

#include "stdio.h"
#include "stdlib.h"

struct aluno{
    char aluno[80];
    int mat;
    float p1,p2,p3;
} joao;

void imprime(struct aluno *a);

int main()
{
    printf("Digite o nome do aluno: ");
    gets(joao.aluno);

    printf("Digite a matricula do aluno: ");
    scanf("%i", &joao.mat);

    printf("Digite as notas do aluno:\n" );
    scanf("%d %d %d", &joao.p1,&joao.p2,&joao.p3);

    imprime(&joao);
    getchar();

    return 0;
}

void imprime(struct aluno* a){
    printf("%s",a->aluno);
}
    
18.05.2015 / 18:30