#include<stdio.h>
void main()
{
char *str="CQUESTIONBANK";
clrscr();
printf(str+9);
getch();
}
The output is BANK. what the printf statement does. Can anyone please explain that?
#include<stdio.h>
void main()
{
char *str="CQUESTIONBANK";
clrscr();
printf(str+9);
getch();
}
The output is BANK. what the printf statement does. Can anyone please explain that?
A string in C is defined as a sequence of char
terminated by a '\0'
. A string isn't a type in C. So, functions handling strings accept a pointer to the beginning of the string (a pointer to char
).
You can do arithmetics on pointers. + x
means increase the pointer by x
elements pointed to. So, str+9
in your example points to the character B
. This pointer is passed as the start of the string to printf()
.
str gives the base address of the pointer to the string.
So normally if you just use printf(str)
it should output CQUESTIONBANK.
But in this case you are printing str+9, ie. printf(str+9)
, so in this case it refers to string starting from the 9th index. In this case the 9th index is B,(C follows 0 indexing), so the string printed is BANK.
printf will always print the string from the passed pointer as starting position till the end of the string, which is stored as '\0'
known as Null Character. If you try printf(str[13])
, it should print '\0'
str
points to a location (address). You can move in any direction over these addresses using +
and -
. So, if str
points to some address, say 0x1002
, then str+1
points to 0x1003
and str-1
points to 0x1001
. (assuming str
is char*
. With other pointer types you move in bigger steps - sizeof(*str)
)
In your example - str
points to an address that holds CQUESTIONBANK
so if you move the pointer 9 steps forward, you move past C,Q,U,E,S,T,I,O,N
and you now point to BANK
. Now using printf
will print from that location resulting in BANK
#include<stdio.h>
void main()
{
char *str="CQUESTIONBANK";
/* clrscr() function will clear the console.*/
clrscr();
/* printf() function, outputs the data. The name of the string, in your case
it is 'str' always points first element of the string which is 'C'. Adding 9 will
'str' point to 'B' character in the string. That's why printf is printing from B on wards.
Similarly adding 10 to 'str' will print from 'A' and so on.*/
printf(str+9);
/* getch() function waits for you to enter any character.*/
getch();
}