Recently for fun I have decided to build a toy programming, compiler and  a low-level register based interpreted vm. While starting to implement the virtual machine I got stuck. The stack which holds the variables and structs I implemented as separate arrays for each type. The problem is when I have a reference to a struct the elements are not aligned, int struct.x might be at address 1, and float struct.y might be at address 0, so accessing the struct by a reference would be impossible, because the indexes are not linear. How could I solve this?stack int:     //other 0: 5,        //x 1: 67stack long:  //y 0: 56stack reference:  //pointer to x, struct access like c array: #00x01For each type I mean for each primitive. I know I could implement it with unions but I want to learn how it is really implemented in java, c++ or c#, that's kind of the point of making a toy language, to better understand what you are programming.
Implement Stack for Toy VM C++
c++;virtual machine;stack
Definitely go with only one stack for everything.You have two options:Declare a StackEntry union which may hold either a primitive data type, (char, bool, int, etc.) or a pointer to a struct, and then make your stack consist of such StackEntry unions.  Each one of these unions will roughly be as large as a machine word.Do it the object oriented way: declare an Object class to represent any kind of object, declare derived classes, one to hold each kind of primitive and one to hold a struct, and make your stack a stack of Object. Each stack entry will be exactly one machine word, (a pointer to an Object,) but then for each stack entry you will have an entire dynamically allocated Object.  This will perform worse, but it will be a lot neater and cleaner, saving you from a lot of headache on the long run.  (Besides, if this is a toy VM, you really should not care about performance.)