C program to print String using Pointer
|In this C Programming example, we will implement the program to print a string using Pointer and print the output on the console.
1. What is a Pointer in C?
A Pointer is a variable whose value is the address of another variable. Just like all other variables we use in the program, pointers are also declared and initialize using C programming nomenclature. Please refer to Pointers in C to learn pointers in detail.
Here is how we can declare a pointer int *p;
Helpful topics to understand this program better are-
2. C Program to print string using pointer
Let’s discuss the execution(kind of pseudocode) for the program to print string using a pointer in C.
- Initially, the program will prompt the user to enter the string.
- Next, we have declared a char array
char str1[100]
and a char pointerchar *ptr
. - In
fgets(str1, 100, stdin)
the input string is stored along with this we have assigned array base address to the pointer like thisptr=str1
. - Next, the input string is passed to the
printString()
wherein thevoid printString()
function there is a while loop that iterates through the string till it reaches thenull
value of the string\0
. - On looping through the string the pointer increments and prints the string on the console.
In this C Programming example, we have discussed how to print string using the Pointer in C.
#include <stdio.h> char str1[100]; char *ptr; void printString() { while (*ptr != '\0') printf("%c", *ptr++); } int main() { printf("Enter any string: "); fgets(str1, 100, stdin); ptr = str1; printf("The input string is: "); printString(); return 0; }
Output Enter any string: Codingeek.com The input string is: Codingeek.com
3. Conclusion
In this C Programming example, we have discussed how to print string using a pointer in C and discussed the steps of the program in detail.
Helpful Links
Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.
Also for the example C programs please refer to C Programming Examples.
All examples are hosted on Github.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?