C Program to Print String using Pointer

June 5, 2021

In this tutorial, we will write a C program to print a String character by character using a pointer variable. To understand this program you should have basic knowledge of the following topics:

  • C Pointers
  • C Array

Program to print a String using Pointer

In the following program we have declared a char array to hold the input string and we have declared a char pointer. We have assigned the array base address (address of the first element of the array) to the pointer and then we have displayed the every element of the char array by incrementing the pointer in the while loop.

#include <stdio.h>
int main()
{
    char str[100];
    char *p;

    printf("Enter any string: ");
    fgets(str, 100, stdin);

    /* Assigning the base address str[0] to pointer
     * p. p = str is same as p = str[0]
     */
    p=str;

    printf("The input string is: ");
    //'\0' signifies end of the string
    while(*p!='\0')
        printf("%c",*p++);

    return 0;
}

admin