Goal: Understand memory addresses, pointer variables, and why C is so powerful (and dangerous).
A pointer is a variable that stores a memory address (not a value). The type tells the compiler what kind of data lives at that address.
int x = 42;
int *ptr = &x; // ptr holds the address of x
printf("%d\n", *ptr); // dereference: prints 42
*ptr = 100; // changes x to 100
printf("%d\n", x); // prints 100
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
printf("x=%d, y=%d\n", x, y); // x=10, y=5
return 0;
}
Write a function void increment(int *p) that adds 1 to the integer pointed to by p. Test it in main.
void increment(int *p) {
(*p)++;
}
int main() {
int a = 5;
increment(&a);
printf("%d\n", a); // 6
return 0;
}
Write a function void square_ptr(int *p) that squares the value pointed to by p.
void square_ptr(int *p) {
*p = (*p) * (*p);
}
What is the difference between int *p and int* p? Is there a difference between int* p, q and int *p, *q?
No functional difference – spacing is stylistic. BUT: int* p, q declares p as pointer to int, q as int (not pointer!). To declare two pointers: int *p, *q.