void-pointer plays the role of Object

Array is a data structure where one can store elements of same data type. But in some languages (e.g. Ruby), we can store elements of different data types in the same array.

arr = [true, 3.14, 1, "hello"]

얼핏 공통점이 없어보이지만 사실 위 자료형들은 모두 Object 클래스를 상속받고 있다. 즉, 모두 Object의 인스턴스이다. 그렇기 때문에 we can store any data that inherits from Object class. これはRubyだけのことではなく、ほとんどの言語で再現できる。例えば、we can simulate this in C/C++ using a void pointer (void*).

Since pointers are fixed in size, we can convert any data into void * and store it into an array of type void pointer.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {
const unsigned SIZE = 4;
  void* arr[SIZE];

  // Store an integer
  arr[0] = malloc(sizeof(int));
  *(int *)arr[0] = 17;

  // Store a float
  arr[1] = malloc(sizeof(float));
  *(float *)arr[1] = 3.14;

  // Store boolean
  arr[2] = malloc(sizeof(int));
  *(int *)arr[2] = 1;

  // Store a string
  arr[3] = malloc(strlen("seventeen") + 1);
  strcpy((char*)arr[3], "seventeen");

  // Print values
  printf("%d\n", *(int *)(arr[0]));
  printf("%.2f\n", *(float *)(arr[1]));
  printf("%s\n", *(int *)(arr[2]) == 1 ? "true" : "false");
  printf("%s\n", (char *)arr[3]);

  // Free allocated memory
  for(int i = 0; i < SIZE; ++i)
      free(arr[i]);

  return 0;
}