diff --git a/zk/Arrays_in_C.md b/zk/Arrays_in_C.md index 5a25d50..7e358b3 100644 --- a/zk/Arrays_in_C.md +++ b/zk/Arrays_in_C.md @@ -3,8 +3,6 @@ tags: - C --- -# Arrays in C - To declare an array in C, you must specify: - the data type of the variables it will store diff --git a/zk/Format_specifiers_in_C.md b/zk/Format_specifiers_in_C.md index 8668a17..8735d54 100644 --- a/zk/Format_specifiers_in_C.md +++ b/zk/Format_specifiers_in_C.md @@ -14,6 +14,7 @@ created: Thursday, February 29, 2024 | 17:41 | `%n` | nothing | | `%i` | integer | | `%f` | float | +| `%p` | pointer | Format specifiers define the type of data to be printed or interpolated in standard output. You need to use format specifiers whenever you are diff --git a/zk/Pointers_in_C.md b/zk/Pointers_in_C.md new file mode 100644 index 0000000..74fad31 --- /dev/null +++ b/zk/Pointers_in_C.md @@ -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; +} +```