Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c printf function dynamic type determination

I am trying to implement a generic stack in c using void pointer to point to the data. the structure looks like this

struct record{
  void* data;
  struct record* previousRecord; 
};

where void pointer data is a pointer to the data a stack position will hold. If I implement a push function like this

struct record* push(struct record* tos, void* data){
  struct record* newtos = (struct record*)malloc(sizeof(struct record));
  newtos->data = data;
  newtos->previousRecord = tos;
  return newtos;
}

and push a couple of integer pointers and string pointers into the stack, is there any way I can print the values referenced by these pointers. My problem is that I have to specify the data type of value to print in the code if I use a printf function but the values stored in the stack can only be determined at run time

like image 708
sidharth sharma Avatar asked Mar 24 '26 07:03

sidharth sharma


1 Answers

If you want to print a data in the correct format, you must know what is its type.

#include <stdio.h>

enum datatype
{
  DATATYPE_STRING, DATATYPE_INTEGER
};

struct record
{
  enum datatype type;
  void *data;
  struct record *next;
};

void print_record(struct record *p)
{
  switch (p->type)
  {
    case DATATYPE_STRING:
      printf("%s\n", (char *)p->data);
      break;
    case DATATYPE_INTEGER:
      printf("%d\n", *(int *)p->data);
      break;
  }
}
like image 117
md5 Avatar answered Mar 26 '26 22:03

md5