C Memory Address
In this page:
What is a Memory Address?
Every piece of data in a running program is stored somewhere in the computer's memory, and that specific location is called its memory address, a number that uniquely identifies where a value physically lives.
Example: What is a Memory Address?
#include <stdio.h>
int main() {
int x = 5;
printf("%p", (void*)&x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Address-of Operator &
The & operator, called the address-of operator, is placed directly before a variable's name to retrieve that variable's memory address instead of its current value.
Example: The Address-of Operator &
#include <stdio.h>
int main() {
int count = 10;
printf("%p", (void*)&count);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing an Address
The %p format specifier is used with printf specifically for displaying memory addresses, and the address is conventionally cast to (void*) before being printed.
Example: Printing an Address
#include <stdio.h>
int main() {
int x = 5;
printf("%p", (void*)&x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Every Variable Has an Address
Every variable in a C program has a memory address, including individual array elements, struct instances, and even function parameters, since each represents a distinct piece of storage.
Example: Every Variable Has an Address
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
printf("%p", (void*)&arr[0]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Addresses and Pointers
A pointer is a variable specifically designed to store a memory address, and understanding what an address is and how & retrieves one is the essential foundation for understanding how pointers work.
Example: Addresses and Pointers
#include <stdio.h>
int main() {
int x = 5;
int *ptr = &x;
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: