Declare strings using pointers in C

We can also declare strings using pointers. In this article, we will learn how to do the same.

Program

#include<stdio.h>
int main()
{
            char name[]="Samarth";
            char *p;
            p=name;
            while(*p != '\0')
            {
                        printf("%c\n",*p);
                        p++;
            }
            return 0;
}

 

Output

Declare strings using pointers in C

Explanation

‘name’ is declared as a string variable of type ‘char’. ‘p’ is a pointer. Since we want ‘p’ to point to the ‘name’ that’s why it is also declared with ‘char’ datatype.

p=name; from this statement, we get to know that ‘p’ stores the address value of ‘name[0]’. Thus, the value of ‘*p’ is equal to the value of ‘name[0]’. Therefore,

*p= ‘S’

Since we know every string is terminated with the null character that’s we use this condition in the ‘while’ loop. When the value of ‘*p’ becomes ‘\0’ (null) the loop will terminate.

In the first iteration the value of ‘*p’ i.e., ‘S’ will be printed.

p++; will update the value of ‘*p’ to ‘*(p+1)’ and in the second iteration ‘a’ will be printed in the next line.

This continues until the pointer encounters with null character and as the value becomes equal to ‘\0’, the loop gets terminated.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.