In C programming, pointers are powerful tools that let you access and manipulate memory directly. In this tutorial, we’ll learn how to use a pointer to print each character of a string along with its memory address.
Objective
- Use a pointer to traverse a string.
- Print the character and its address using pointer arithmetic.
Example C Program
#include <stdio.h>
int main() {
char str[] = "Hello";
char *ptr;
ptr = str; // Pointer points to the first character
printf("Character | Address\n");
printf("---------------------\n");
while (*ptr != '\0') {
printf(" %c | %p\n", *ptr, ptr);
ptr++;
}
return 0;
}
Sample Output
Character | Address
---------------------
H | 0x7ffee5b8c730
e | 0x7ffee5b8c731
l | 0x7ffee5b8c732
l | 0x7ffee5b8c733
o | 0x7ffee5b8c734
(Note: The actual address values will differ each time you run the program.)
Explanation
char str[] = "Hello";
creates a string.char *ptr = str;
sets the pointer to the beginning of the string.- The loop continues until
*ptr
is'\0'
, the null terminator. *ptr
prints the character,ptr
prints the address.
Pointer Concepts Used
- Pointer arithmetic (
ptr++
) - Dereferencing (
*ptr
) - String traversal using a pointer
Key Takeaways
- Pointers can directly access memory locations of characters.
- Strings in C are arrays of characters ending with
\0
. - This method is useful for understanding how strings are stored in memory.
Conclusion
Using pointers to print characters and their addresses gives you a deeper understanding of how strings are stored and accessed in C. It’s an essential concept for working with arrays, dynamic memory, and low-level data handling in C.