Introduction to Pointers
Understanding Memory and Pointers
A pointer is one of C's most powerful features. To understand it, first picture memory as a long street of numbered houses. Every variable lives at a numbered location called its address.
The Address-of Operator
The & operator gives you the memory address of a variable.
int age = 19;
printf("Value: %d\n", age);
printf("Address: %p\n", &age);Declaring a Pointer
A pointer variable stores an address rather than an ordinary value. You declare one by adding a * to the type.
int age = 19;
int *ptr = &age; // ptr now holds the address of ageRead int *ptr as “ptr is a pointer to an int”.
The Dereference Operator
Putting * in front of a pointer dereferences it — it follows the address to reach the actual value stored there.
int age = 19;
int *ptr = &age;
printf("%d\n", *ptr); // 19 the value ptr points to
*ptr = 25; // change age through the pointer
printf("%d\n", age); // 25 age was modifiedNotice the two uses of *. In a declaration it creates a pointer. In an expression it dereferences a pointer. They look the same but mean different things.
Why Pointers Matter
- They let a function change a caller's variable, not just a copy.
- They make it possible to work with arrays and strings efficiently.
- They are the foundation of dynamic memory and data structures like linked lists.
Pointers in Functions
Normally C passes a copy of a value to a function. By passing an address instead, the function can modify the original variable.
void setToTen(int *p) {
*p = 10;
}
int main(void) {
int x = 0;
setToTen(&x);
printf("%d\n", x); // 10
return 0;
}Never dereference a pointer that does not point to valid memory. An uninitialised or NULL pointer dereference typically crashes the program.
Discussion
0No comments yet — be the first to leave one!