How to do a pointer struct for a function that prints the struct itself in C

Asked

Viewed 450 times

-1

I have a structure:

struct conteudo{
    tipo valor;  //valor qualquer
    void (func*)(void*); //ponteiro para função que imprime a propria estrutura
};

I would like to know how to call this function to the cell itself, since conteudo->func(conteudo); doesn’t work.

1 answer

1

The C language is not object oriented, so it does not have a pointer like the this for a method to be able to access members of a struct.

The way I found to do this is this, you create a struct with a pointer to a print function, declare a print function outside of the struct, in main when creating the struct you assign its values and print function to the pointer of the struct, and when calling the struct pointer you need to assign in the parameter the struct that needs to be written, this is redundant, but it’s the closest I can do with C what I would do with an OO language.

#include <stdio.h>

struct Conteudo {
  int valor;

  void (*print)(struct Conteudo* conteudo);
};

void print(struct Conteudo* conteudo) {
  printf("Valor: %d\n", conteudo->valor);
}

int main() {
  struct Conteudo conteudo;

  conteudo.valor = 10;

  conteudo.print = print;

  conteudo.print(&conteudo);

  return 0;
}

Browser other questions tagged

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