Arrays
CaffeineC doesn't have builtin support for arrays, but they are still possible to create.
Defining a new array
Finding out how much memory we need
To create a new array, you have to know what data type will be stored inside. You will then have to find out, or calculate the memory (in bytes) that will be required to store one instance of the type. So for example a 64 bit integer (i64
type) requires 8 bytes. If you want to store 10 64 bit integers, you will need 10 x 8 bytes of memory.
Allocating the memory
To allocate the memory required, we will need to use the malloc
function from C. To use it in CaffeineC, we need to define the external function. We can do this using this simple syntax
extern func malloc(size: i64): *i8;
Then in our main function we can call the function to allocate the necessary memory
package main;
extern func malloc(size: i64): *i8;
func main() {
var mem: *i8 = malloc(10 * 8); // 10 x 8 bytes
}
Casting the allocated memory to the correct data type
Next we need to cast our allocated memory to the correct data type using the bitcast expression.
package main;
extern func malloc(size: i64): *i8;
func main() {
var mem: *i8 = malloc(10 * 8); // 10 x 8 bytes
var array: *i64 = (mem): *i64; // Casting to a pointer to i64
}
We can also simplify this to work as a one-liner:
package main;
extern func malloc(size: i64): *i8;
func main() {
var mem: *i64 = (malloc(10 * 8)): *i64; // Allocate and cast
}
Accessing elements in the array
Once we have created our array, accessing it is pretty simple. You can do it using [] just like in other languages.
package main;
extern func malloc(size: i64): *i8;
extern func printf(fmt: *i8): i32; // Defining the printf function
func main() {
var mem: *i64 = (malloc(10 * 8)): *i64; // Allocate and cast
mem[0] = 24; // Sets the i64 at index 0 to 24
printf("%d\n", mem[0]); // Reads and prints the valu of the i64 and index 0
}
Last updated
Was this helpful?