Pointers
Understanding memory addresses
Introduction
In this lesson, you'll learn about pointers in C. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with understanding memory addresses.
C has its own approach to understanding memory addresses, which we'll explore step by step.
The C Way
Let's see how C handles this concept. Here's a typical example:
// C pointers - explicit memory addresses
int arr[5]; // array on stack
int* heapArr = malloc(5 * sizeof(int)); // on heap
Person p; // struct on stack
Person* pp = &p; // pointer to p
// Must explicitly dereference
(*pp).name = "Alice"; // or: pp->name = "Alice"
arr[0] = 42;
// Pass pointer to modify
void modify(Person* p) {
p->name = "Bob"; // modifies original
}Comparing to Java
Here's how you might have written similar code in Java:
// Java references - hidden pointers
int[] arr = new int[5]; // reference to array
Person p = new Person(); // reference to object
// References are automatically dereferenced
p.name = "Alice";
arr[0] = 42;
// Pass by reference (for objects)
void modify(Person p) {
p.name = "Bob"; // modifies original
}You may be used to different syntax or behavior.
* declares a pointer, & gets the address
You may be used to different syntax or behavior.
-> accesses members through a pointer
You may be used to different syntax or behavior.
Pointers can be null (NULL) or invalid
You may be used to different syntax or behavior.
Pointer arithmetic is allowed in C
Step-by-Step Breakdown
1. Pointer Basics
A pointer holds a memory address. Use * to declare, & to get address, * to dereference.
int x = 42;
int* ptr = &x; // ptr holds address of x
printf("%p", ptr); // prints the address
printf("%d", *ptr); // prints 42 (dereferenced)
*ptr = 100; // x is now 1002. Pointers and Structs
Use -> to access struct members through a pointer.
struct Person {
char name[50];
int age;
};
struct Person p = {"Alice", 30};
struct Person* ptr = &p;
// Two equivalent ways to access:
(*ptr).age = 31; // dereference then access
ptr->age = 31; // arrow operator (preferred)3. Pointer Arithmetic
Pointers can be incremented to move through arrays.
int arr[5] = {10, 20, 30, 40, 50};
int* p = arr; // points to first element
printf("%d", *p); // 10
printf("%d", *(p+1)); // 20
printf("%d", *(p+2)); // 30
p++; // moves to next int (adds sizeof(int))
printf("%d", *p); // 20Common Mistakes
When coming from Java, developers often make these mistakes:
- * declares a pointer, & gets the address
- -> accesses members through a pointer
- Pointers can be null (NULL) or invalid
Key Takeaways
- Pointers store memory addresses
- & gets address, * dereferences
- -> accesses struct members via pointer
- Pointer arithmetic moves by sizeof(type)