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

Asked

Viewed 263 times

0

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

In other words, it is a generic structure to create a table of anything.

My problem is in the insert part of the element, as I will tell the function inserir() that I’m passing an element that may be of any kind?

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?
    ...
}

2 answers

1


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
  ...
}
  • Show! Now it worked. A question, why should one initialize with the memset command? It would be for safety or because it is a good practice?

  • 1

    you need to initialize the pointers, otherwise they will have "junk" values (which was already in memory in those placements) and will point to invalid memory addresses

0

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

Browser other questions tagged

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