C Program to Print Address and Character of String Using Pointer

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.

Previous Article

C Program to Swap Two Values Using Pointers

Next Article

C Program to Access Array Elements Using Pointer

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨