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.

  1. Initially, the program will prompt the user to enter the string.
  2. Next, we have declared a char array char str1[100] and a char pointer char *ptr.
  3. In fgets(str1, 100, stdin) the input string is stored along with this we have assigned array base address to the pointer like this ptr=str1.
  4. Next, the input string is passed to the printString() wherein the void printString() function there is a while loop that iterates through the string till it reaches the null value of the string \0.
  5. 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!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index