How can I pass a parameter, of any type, to a generic vector? - C

I have a structure of type TTabelaX, which is basically a table that I will store elements of any type, that is, I can create a table to store an element type TCarro, with plate and color, then I can use the same structure to create a table to store a type TPessoa, with name and cpf.

In other words, it is a generic structure for creating a table of anything.

My problem is in the part of inserting the element, How am I going to tell the function inserir() that I'm passing an element that can be of any type?

typedef struct tabelax TTabelaX;
struct tabelax{
    int max;
    int pos;
    void** tabela;
};

TTabelaX*cria_tabela(int tam){
    // Aloquei a estrutura e passei o endereço pra aux
    TTabelaX* aux = (TTabelaX*)malloc(sizeof(TTabelaX));
    // Tabela aponta p/ um vetor do tipo void*, tornando genérico
    aux->tabela = (void**)malloc(sizeof(void*) * tam);
    aux->max = tam;
    aux->pos = 0;    
    return aux;
}

void inserir(TTabelaX* aux, ???){//<--como passar um parâmetro sem saber seu tipo?
    ...
}
Author: Filipi Maciel, 2019-04-03

2 answers

Use pointer to void.

TTabelaX*cria_tabela(int tam) {

  // Aloquei a estrutura e passei o endereço pra aux
  TTabelaX* aux = (TTabelaX*)malloc(sizeof(TTabelaX));

  // Tabela aponta p/ um vetor do tipo void*, tornando genérico
  aux->tabela = (void**)malloc(sizeof(void*) * tam);
  memset(aux->tabela, 0, sizeof(void*) * tam); // <------- inicializar os ponteiros
  aux->max = tam;
  aux->pos = 0;    
  return aux;
}

void inserir(TTabelaX* aux, void* pX) { // <-- declare como um ponteiro para void
  ...
}
 1
Author: zentrunix, 2019-04-03 13:58:54

You can declare the element as a string (if it is c++) or as a char vector. Both accept values of any kind.

 0
Author: Nyelthon Refatti, 2019-04-03 12:58:38