Pointers
A pointer is simply a variable that stores the memory address of another variable. Instead of holding a direct value, it holds the location in the computer's memory where the actual value is stored.
type* identifier;
type *identifier;
type * identifier;
* stays in the middle.Dereferencing
int num = 13;
int *ptr = #
print("address: {}\n", ptr); # this will output the memory address: 0x3454...
print("value: {}\n", *ptr); # this will output the value stored at that memeory address: 13
Passing By Reference
By default, arguments are passed by value, meaning a copy of the data is passed directly to the function. While this approach ensures that the original data remains unchanged, it can be inefficient for large data structures. In such cases, passing the address of the data is more practical, either to improve performance or to allow the function to modify the original value.
Example:
void add_one(int* ptr){
*ptr += 1;
}
int main(){
int num = 1;
println("before: {}", num); # before: 1
add_one(num);
println("after: {}", num); # after: 2
return 0;
}
Notice that in order to pass an argument by reference, the function parameter must be declared as a pointer, allowing the function to recieve and operate on the address of the original data. In the above example, variable ptr is declared as an int pointer. The variable num is passed normally to the function add_one, in this case however, the address of num is being served instead of its value.
Returning An Address
not yet documented!
Pointer Arithmetic
Unlike regular maths arithmetic, only addition + and substraction - are allowed.
for pointer arithmetic.
Suppose ptr is a pointer pointing to a particular type, then
ptr++;
ptr--;
ptr += n;
ptr -= n;
ptr1 = ptr2 + n;
ptr1 = ptr2 - n;