int main()
{
char *p,c;
for(p="Hello World";c=*p;++p)
{
printf("%c",c);
}
}
In the above code,i know that ++p will make pointer ‘p’ point to next character in the “Hello World”.And i also know that there is no boundary checking performed on arrays in C or C++.The output of the program is ‘Hello World’. How am i able to test conditions using
c=*p;
What does ‘c=*p’ return.As far as my understanding goes, when ‘++p’ reaches the end of the ‘hello world’, pointer ‘p’ should point to some garbage value and the loop should print some garbage values.
C strings are by definition terminated by a NULL character
'\0', if it is a string then it has to end it in a NULL. thereforec = *pwill point to a NULL character when the string ends, which is in your case the immediately next character of'd'. And the NULL character in the ASCII table has an integer value 0, which evaluates to false and gets out of theforloop.Note that if a C string does not end in a NULL character (then at first it is not a C string), then basically there is no way of detecting that it is a string, as it will be stores as a sequence of bytes. In that case it will be simply a byte array or a string, will depend on how we interpret.
Also not that
c = *pdoes not return anything, it is an expression and it is evaluated.e = *ptransfers the value pointed by the current value ofpinto the varc, the value of which is the final evaluation of the expression.