C - How to pass an array in which it contains pointers to struct as a function parameter?

Asked

Viewed 198 times

2

First I created a struct vector. Next I created a pointer vector, in which each element of this vector points to each element of the struct vector.

Finally, I need to pass both (the struct vector and the pointer vector) as parameters of a function. I have tried some ways searching here on the site, but it gave error. I just don’t know how to do it.

Follows the code:

#include <stdio.h>
#include <string.h>

struct dados
{
   int dia, mes, ano;
   char nome_mes[50];
   char remetente[100];
   char destinatario[100];
};

void ordenar(struct dados *cartas, ***O QUE COLOCAR AQUI***, int n){
   //DUVIDA NESSA FUNÇÃO
}


void main(){

    int n, i;
    char lixo[5];
    scanf("%d\n", &n);

    struct dados cartas[n], *ponteiros[n];

    for(i = 0; i < n; i++){
    ponteiros[i] = &cartas[i];
    }

    for(i = 0; i < n; i++){
        scanf("%d de ", &cartas[i].dia);
        scanf("%s", cartas[i].nome_mes);
        scanf("%s", lixo);
        scanf(" %d\n", &cartas[i].ano);
        gets(cartas[i].remetente);
        gets(cartas[i].destinatario);
    }

    //DÚVIDA AQUI !!!
    ordenar(cartas, ponteiros, n);

}

How to do this?

1 answer

2

You have two possible syntaxes to do this. The first one is identical to the one you used for the parameter cartas thus:

void ordenar(struct dados *cartas, struct dados **ponteiros, int n){
//                                               ^---

As being a pointer pointer.

Another way is to use pointer array notation, almost equal to the one you used when declaring:

void ordenar(struct dados *cartas, struct dados *ponteiros[], int n){
//                                              ^---------^

In both forms it is always necessary to pass the size to be able to go through the amount of elements that exist, and the use of the parameter within the function a will be equal.

As a last aside, if the code is not for playful and/or educational purposes, remember that the function already exists qsort to sort vectors, which greatly simplifies the work.

Browser other questions tagged

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