Print String Elements using Pointers in C Language

Print-String-Elements-using-Pointers-in-C-Language

Print String Elements using Pointers Program Description:

Write a Program to demonstrate how to print string elements using pointers in c programming language. The program should accept a string from the user and print all string characters using a pointer. To access the string elements, we will use standard pointer notation (by dereferencing the pointer) as well as pointer subscript notation.

Here is the example input and output of the program.

Example Input and Output:

Input:

Enter a string : code

Output:

chPtr[0]:c
chPtr[1]:o
chPtr[2]:d
chPtr[3]:e

Prerequisites of the program:

Please go through the following C tutorials to better understand the program.

Program to Print string elements using pointers in C Language:

Here we used the character pointer chPtr to print the elements of the string inputStr.

We started the program by declaring a string called inputStr to hold the input string with the SIZE characters. Then we prompted the user to provide the string and stored it in the inputStr using a gets function.

Then we created a character pointer chPtr and initialized the chPtr with the inputStr string.

char * chPtr = inputStr;

Finally, We used a for loop to iterate over the characters of the input string inputStr and accessed/printed the string elements using the pointer chPtr and index ( i) – *(chPtr+i)

Program Output:

Let’s compile and run the program using your favorite compiler. We are using the GCC compiler on ubuntu Linux OS.

As we can see from the above output, The program is properly printing the string elements using the pointer.

Method 2: Print string elements using pointers subscript notation in C:

Instead of using the *(chPtr+i) we can simply use the pointer subscript [ ] notation chPtr[i] ( Both these notations are the same). Here is the program to print the string characters using pointer subscript notation in C programming language.

Note that, We used the pointer subscript notation chPtr[i] in this example.

Program Output:

Compile the program.

$ gcc print-string-ptr.c

Run the program. ( ./a.out)

program-to-print-string-characters-using-pointers-in-c-programming-language

As we can see from the above output, We are getting the expected output.

Related Pointers Programs:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply