eolas/zk/Pointers_in_C.md
2025-12-15 17:26:02 +00:00

64 lines
1.1 KiB
Markdown

---
tags:
- C
---
A pointer is a reference to the address of a variable in memory.
```c
int num = 27;
int *ptr_to_num = #
printf("%i\n", num);
// 27
printf("%p\n", ptr_to_num);
// 0x7ffeb44f7eac
```
We indicate that we are creating a pointer with `*`.
We then retrieve the memory address with `&`.
We can 'de-reference' back to the value with:
```c
printf("%i\n", *ptr_to_num);
// 27
```
## Why are pointers even necessary?
In other languages you can do something like:
```js
let num = 27;
console.log(num);
// 27
function modify(theNumber) {
theNumber = 28;
return theNumber;
}
```
In C, you cannot use functions to modify variables that live outside of them
(e.g. in higher scope).
If you did the above with C, `num` would still be `27` after the function call.
This is bcause arguments are passed by value, not by reference to the item in
memory that the variable refers to.
So, to modify the actual value in memory, you invoke pointers.
The above JavaScript in C would be:
```c
int num = 27
int modify(int *the_number) {
*the_number = 28;
return the_number;
}
```