Error when trying to pass a struct by C reference?

Asked

Viewed 276 times

3

I’m taking pointer class and I’m trying to do the following exercise:

Consider a enrollment of students enrolled in a discipline, with the following information for each student:

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

(a) Define a structure in C, called 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 student’s name and another line with the average obtained in the three tests. This function must follow the following prototype:

void imprime (struct aluno* a);

It’s just that there’s a glitch in the code:

'#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'|

2 answers

3


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

Then, inside the function main() the definition of the struct aluno; which shall take effect from then until the end of the programme.

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

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

The best solution is to pass the definition of struct aluno for before any use; for immediately after #includes.

  • Exactly that, thanks mt!!!

0

Analyzing 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);
}

Browser other questions tagged

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