code example like this:
#include<stdio.h>
void main()
{
char *s={"abcd"};
do {
printf("%d\n",++s);
} while(*s);
}
Where does the pointer s point when the loop do ends?How does it work?
code example like this:
#include<stdio.h>
void main()
{
char *s={"abcd"};
do {
printf("%d\n",++s);
} while(*s);
}
Where does the pointer s point when the loop do ends?How does it work?
In C, zero is equivalent to false
. So when *s
points to the terminator character in the string (a zero), the loop stops.
"abcd" is stored in memory in 5 consecutive bytes: 'a' 'b' 'c' 'd' '\0'
.
The last byte, zero, terminates the loop since zero is false in C.
First of all, you should not use %d
for formatting a pointer, it is for integers, not for pointers. Use %p
instead.
This line-
char *s={"abcd"};
initializes the string with '\0'
as the last character.
Your programs loops through each character (from 2nd to last) of the string an prints the address of where they are stored in the memory. Since it is a do-while
loop, the condition checking is done after the execution of the body of the loop.
NOTE: It does NOT print the address of the first character because-
printf("%d\n",++s);
this line (due to prefix increment) increments the pointer to the next character before passing its value to printf
. So when the body of the loop is executed for the first time, the address of the second character(b
) is printed.
Now the condition part of the loop checks whether character at pointed by s
(the character can be referred to by *s
) is non-zero.
As the string has '\0'
as the last character (which has an integer value of 0
), the loop terminates when it reaches the last character.
The output of your program (with %d
changed to %p
) will be something like but NOT exactly same as-
0x40061d
0x40061e
0x40061f
0x400620
Note that only 4 addresses are printed (from 'b'
to '\0'
, the address of 'a'
is not printed). To do that you should try this-
#include<stdio.h>
main()
{
char *s={"abcd"};
do {
printf("%p\n",s++);
} while(*s);
printf("%p\n", s); // to print the address of the '\0' character.
}