-1

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?

ShuklaSannidhya
  • 8,572
  • 9
  • 32
  • 45
Z-Cao
  • 9
  • 1

3 Answers3

4

In C, zero is equivalent to false. So when *s points to the terminator character in the string (a zero), the loop stops.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
3

"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.

nullptr
  • 11,008
  • 1
  • 23
  • 18
0

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.
}
ShuklaSannidhya
  • 8,572
  • 9
  • 32
  • 45
  • Thanks,but why does the result keep constant when I change abcd into other four chars? – Z-Cao May 19 '13 at 23:31
  • @Z-Cao It is printing the address of the characters. Address may or may NOT change. It does not matter what character it points to. To print the character use `printf("%c\n", *s);`. – ShuklaSannidhya May 20 '13 at 03:25