# 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

```go
extern func malloc(size: i64): *i8;
```

Then in our main function we can call the function to allocate the necessary memory

```go
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.&#x20;

```go
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:

```go
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.

```go
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
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://c.vypal.me/high-level-functionality/arrays.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
