pointers in C
This commit is contained in:
parent
cb127a0068
commit
2ca5b0d98a
3 changed files with 65 additions and 2 deletions
|
|
@ -3,8 +3,6 @@ tags:
|
||||||
- C
|
- C
|
||||||
---
|
---
|
||||||
|
|
||||||
# Arrays in C
|
|
||||||
|
|
||||||
To declare an array in C, you must specify:
|
To declare an array in C, you must specify:
|
||||||
|
|
||||||
- the data type of the variables it will store
|
- the data type of the variables it will store
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ created: Thursday, February 29, 2024 | 17:41
|
||||||
| `%n` | nothing |
|
| `%n` | nothing |
|
||||||
| `%i` | integer |
|
| `%i` | integer |
|
||||||
| `%f` | float |
|
| `%f` | float |
|
||||||
|
| `%p` | pointer |
|
||||||
|
|
||||||
Format specifiers define the type of data to be printed or interpolated in
|
Format specifiers define the type of data to be printed or interpolated in
|
||||||
standard output. You need to use format specifiers whenever you are
|
standard output. You need to use format specifiers whenever you are
|
||||||
|
|
|
||||||
64
zk/Pointers_in_C.md
Normal file
64
zk/Pointers_in_C.md
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
---
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
```
|
||||||
Loading…
Add table
Reference in a new issue