In C programming, pointers are variables that store memory addresses. Understanding pointers is essential to mastering C. This tutorial demonstrates a simple program to print the address of a variable using a pointer.
Objective
- Declare a variable.
- Declare a pointer to store its address.
- Use the pointer to print the address of the variable.
Example Program
#include <stdio.h>
int main() {
int number = 50;
int *ptr;
// Assign address of number to ptr
ptr = &number;
// Print the address using pointer
printf("Address of variable 'number' = %p\n", ptr);
return 0;
}
Sample Output
Address of variable 'number' = 0x7ffee3b4891c
(Note: Address may vary on your system.)
Explanation
int number = 50;
→ A simple integer variable.int *ptr;
→ Pointer to an integer.ptr = &number;
→ Store the address ofnumber
inptr
.%p
is used to print a pointer (memory address).
Why It Matters
Understanding pointers allows you to:
- Manage memory directly.
- Pass variables by reference to functions.
- Handle arrays and dynamic memory.
Tip for Beginners
Try modifying the value of the variable using the pointer:
*ptr = 100;
printf("New value of number = %d\n", number); // Output: 100
This will help you understand how pointers can also access and modify values.
Conclusion
Using pointers to access and print the address of variables is a fundamental concept in C. Mastering this helps you work more efficiently with memory and advanced data structures.
This simple pointer example is the first step toward more advanced programming concepts like dynamic memory, arrays, and structures.