C program to print a string character by character using pointer

In this C program, we are going to learn how to read and print (character by character) a string using pointer?
Here, we have two variables, str is a string variable and ptr is a character pointer, that will point to the string variable str.
First of all, we are reading string in str and then assigning the base address of str to the character pointer ptr by using ptr=str or it can also be done by using ptr = &str[0].
And, finally we are printing the string character by character until NULL not found. Characters are printing by the pointer *ptr.
Consider the program
/*C program to print a string using pointer.*/
#include <stdio.h>
int main()
{
    char str[100];
    char *ptr;
     
    printf("Enter a string: ");
    gets(str);
     
    //assign address of str to ptr
    ptr=str;
     
    printf("Entered string is: ");
    while(*ptr!='\0')
        printf("%c",*ptr++);
         
    return 0;
}

Advertisements

Output
Enter a string: This is a test string.
Entered string is: This is a test string.

Comments

Popular posts from this blog

C Program to Check Whether a Character is an Alphabet or not

C Program to Calculate the Sum of Natural Numbers

C Program to Count Number of Digits in an Integer