How do I pass an array of structure pointers to a function?

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

#define NUM_NOTAS 5
#define TAM_NOME 20


struct Aluno{
 char nome[TAM_NOME];
 int numero;
 int notas[NUM_NOTAS];
};
void preenche(struct Aluno* lista[], int tam){
 int i;
 int j;
 for(i=0;i<tam;i++){
    printf("Nome:");
    scanf("%s",&(lista[i])->nome);
    printf("Número:");
    scanf("%d",&(lista[i])->numero);
    for(j=0;j<5;j++){
        printf("Introduza a nota %d:",j);
        scanf("%d",&(lista[j])->notas[j]);
    }
 }
}



int main(int argc, char** argv) {
 struct Aluno* lista[5];
 preenche(&lista[5],5);



 return (EXIT_SUCCESS);
}

I would like to know how to pass struct Aluno* lista[5]; to the preenche function, because the way I'm doing the function does not read the array.

    
asked by anonymous 04.01.2017 / 16:31

2 answers

2

I think what you r that actually is this:

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

#define NUM_NOTAS 5
#define TAM_NOME 20

struct Aluno {
 char nome[TAM_NOME];
 int numero;
 int notas[NUM_NOTAS];
};

void preenche(struct Aluno lista[], int tam) {
    for (int i = 0; i < tam; i++) {
        printf("\nNome:");
        scanf("%s", lista[i].nome);
        printf("\nNúmero:");
        scanf("%d", &lista[i].numero);
        for (int j = 0; j < NUM_NOTAS; j++) {
            printf("\nIntroduza a nota %d:", j);
            scanf("%d", &lista[i].notas[j]);
        }
    }
}

int main(void) {
    struct Aluno lista[2];
    preenche(lista, 2);
    printf("\n----------------------");
    for (int i = 0; i < 2; i++) {
        printf("\nNome:");
        printf("%s", lista[i].nome);
        printf("\nNúmero:");
        printf("%d", lista[i].numero);
        for (int j = 0; j < NUM_NOTAS; j++) {
            printf("\nNota %d:", j);
            printf("%d", lista[i].notas[j]);
        }
    }
    return (EXIT_SUCCESS);
}

See running on ideone .

Note that you do not have to have this pointer. And if he does, he would need to allocate memory for him. Then just pass the variable itself which is already an array ( it's actually a pointer in the end ). You can simplify doing this and solve what you need.

I solved some other minor problems. And I had to print the result to see that it is correct.

If you want to use a pointer, then use a pointer instead of the array . In this case basically the change must be in the declaration of the variable that must allocate memory in another way. For a pointer to array need to have sense in this, which is not the case. I've responded with array because that's what's in tag , and the code seems to indicate that it's important, whereas the pointer does not.

    
04.01.2017 / 17:11
0

Just change preenche(&lista[5],5); to preenche(lista, 5); .

Oh, I think in your scanf("%d",&(lista[j])->notas[j]); you really wanted scanf("%d", &(lista[i])->notas[j]); . That is, you used j instead of i .

    
04.01.2017 / 16:50