3

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

sidharth sharma
  • 3,025
  • 6
  • 23
  • 20

2 Answers2

4

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;
  }
}
md5
  • 23,373
  • 3
  • 44
  • 93
2

With address how would you know the type of data, it can be string or an integer address:

But you can keep an extra field in your record definition about type of value stored in data part, like below:

typedef enum { STRING, INT, CHAR} type;
struct record{
  type t;
  void* data;
  struct record* previousRecord; 
};

and write a common print function :

int print(struct record  *r){  

  switch(r->t){
     case CHAR:     return printf("%c", *((char*)(r->data)));
     case INT:      return printf("%d", *((int*)r->data));        
     case STRING:   return printf("%s", (char*)r->data);        
     default:       return printf("Error");
  }
} 

Here is a Project/A book that can be very helpful to write generic code in C.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • I don't think your print function is correct. `r->data` is a pointer, never a char or int. You need eg. `*(char*)r->data` in the CHAR case. – Paul Hankin Jan 13 '13 at 11:02
  • @Anonymous Yes you are correct ...And I am using %s and %c with same form r->data that wrong! ..Thanks Anonymous! ...Can you please check again (because complex typecast included) – Grijesh Chauhan Jan 13 '13 at 13:48