In this program, we are going to follow up topic of pointer and how do we use it to print character in strings? So let’s first consider that we have taken a string of 6 characters and we want to access each character and print it but not directly rather using pointer. So pointers are used when we want to access some data not directly but indirectly through some other link which points to original data.
For example, I have stored string in
We will get to know more about this when we see program source code.
This program is somewhat similar to previous program we have done for printing each character of string.
Pointers, string, array, input output functions
We will take user input as usual from command prompt to keep input dynamic and store the string inside character array.
As we are going to make use of pointer to access each character, declare a character pointer and for doing that suffix pointer variable name by asterisk which will look like
char *pointer_var_name. * is called dereference character when used with pointer and set address of character array or string to pointer so that pointer points to first character in array (string is character array).
In this example we are going to use while loop to iterate loop
Inside while loop body, we will add
So when we increment address of p then it will increment address that will eventually point to next character. (each character is of 1 byte and address gets incremented by 1 so it points to next character which is at new incremented address)
Step by step approach:
First declare the array of character type, let’s say
Use while loop for iterating through array till character ‘/0’ is not reached. ‘/0’ indicates end of array or last character in array after string and it is present there just to indicate end of array. While loop condition looks like
Inside while loop we will add printf() function to print character with format specifier %c and dereferencing pointer
Increment the character pointer
printf("\n provide input string:");
printf("Address of string = %p\n",CharArr);
printf("Character = %c\t",*pt);
printf("Address = %p\n",pt);
provide input string:cprograms
Address of string = 000000000062FE00
Character = c Address = 000000000062FE00
Character = p Address = 000000000062FE01
Character = r Address = 000000000062FE02
Character = o Address = 000000000062FE03
Character = g Address = 000000000062FE04
Character = r Address = 000000000062FE05
Character = a Address = 000000000062FE06
Character = m Address = 000000000062FE07
Character = s Address = 000000000062FE08