Struct with vector not working

Asked

Viewed 112 times

1

I’m trying to use vectors and struct, but it’s not working.

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

typedef struct Atleta {

    float notas[5];

} atleta;

void receberNotas(atleta* l) {
    int i;
    for(i=0; i<5; i++) {
        printf("Digite %d nota: ", (i+1));
        scanf("%f", &l[i].notas);
    }
}

void mostrarNotas(atleta *l) {
    int i;
    for(i=0; i<5; i++) {
        printf("\n%.2f", l[i].notas);
    }
}
int main()
{
    atleta *a;
    receberNotas(&a);
    mostrarNotas(a);
    return 0;
}

I could not use this operator -> to access.

1 answer

2


There are several problems. I am assuming that an athlete has 5 grades. If not, there are more things wrong.

You have to allocate the memory to the structure. I preferred to opt for dynamic allocation with malloc(). And don’t need to spend with &, he’s already a pointer.

Access to the index shall be made on notas and not on the athlete’s object, in case it was used l (bad name of variable). Unless there are 5 athletes with a note each (it would be strange to use a structure for this).

And access to the member should be done with the operator -> since it is a reference.

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

typedef struct Atleta {
    float notas[5];
} atleta;
void receberNotas(atleta* l) {
    for (int i = 0; i < 5; i++) {
        printf("Digite %d nota: ", (i + 1));
        scanf("%f", &l->notas[i]);
    }
}
void mostrarNotas(atleta *l) {
    for (int i = 0; i < 5; i++) printf("\n%.2f", l->notas[i]);
}
int main() {
    atleta *a = malloc(sizeof(atleta));
    receberNotas(a);
    mostrarNotas(a);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

See the Actual difference between point operator (.) and arrow operator (->) in C?

  • I couldn’t remember some concepts, I went for a while without studying.

Browser other questions tagged

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