Pointers: Basics & Memory
Pointers are variables that store the memory address of other variables. Pointers are C's most famous and powerful feature, providing direct access to memory layouts.
1 Memory Addresses and Pointer Variables
Every variable exists at a specific location in memory, represented by a hexadecimal address (e.g. `0x7ffeefbff568`). To work with addresses, we use two key operators:
- Address-of Operator (`&`): Retrieves the memory address of a variable.
- Dereferencing Operator (`*`): Accesses or modifies the value stored at the address a pointer is pointing to.
2 Declaring and Dereferencing Pointers
Let's run a program declaring pointers, displaying addresses, and modifying values via dereferencing:
C — Pointer Basics
▶ Run Code
#include <stdio.h>
int main() {
int num = 42;
int *ptr = # // ptr stores the address of num
// Print values and addresses (%p is format specifier for addresses)
printf("Value of num: %d\n", num);
printf("Address of num (&num): %p\n", (void*)&num);
printf("Value stored in ptr (address): %p\n", (void*)ptr);
printf("Dereferenced ptr (*ptr): %d\n", *ptr);
// Modify num's value via the pointer dereference
*ptr = 99;
printf("New value of num after *ptr = 99: %d\n", num);
return 0;
}
3 Code Challenge
Challenge: Write a program that declares a double variable `temp = 36.6`, a pointer pointing to it, and prints the variable's value. Then modify the temperature to `37.2` using dereferencing, and print the updated temperature.