jweinst1
7/14/2017 - 11:40 PM

setting and getting void* in c

setting and getting void* in c

#include "stdio.h"
#include "stdlib.h"

//example for token construction

//data token
typedef struct
{
  int type;
  void* data;
} ConsToken;

//int value
typedef struct
{
  int val;
} IntVal;

typedef struct
{
  int* vals;
} IntSeq;

ConsToken* makeint()
{
  ConsToken* cst = malloc(sizeof(ConsToken));
  cst->type = 1;
  cst->data = malloc(sizeof(int));
  //dereference and cast
  *(int*)cst->data = 4;
  return cst;
}

ConsToken* makeintseq()
{
  ConsToken* cst = malloc(sizeof(ConsToken));
  cst->type = 2;
  cst->data = malloc(sizeof(int) * 3);
  //dereference and cast
  ((int*)cst->data)[0] = 4;
  ((int*)cst->data)[1] = 88;
  return cst;
}

void printfirst(ConsToken* cst)
{
  printf("First value is %d\n", ((int*)cst->data)[0]);
}



int main(void) {
  ConsToken* cst = makeintseq();
  printfirst(cst);
  return 0;
}