In the following program,
int main()
{
char a[] = "azmruf";
char *ptr = a;
ptr += 5;
//Now ptr points at 'f'
printf("%c", --*ptr--); //e got printed. Bcos of post increment now ptr in u.
printf("%c", *ptr); // so 'u' got printed now.
// Next --*--ptr becomes --*(--ptr),
// ptr is moved to r, then --r i.e q is printed, but pointer should
// be in 'r'
printf("%c", --*--ptr);
//Im here getting 'q' only instead of 'r'. There is no 'q' in my string.(??!!!)
printf("%c", *ptr);
return 0;
}
How i’m getting ‘q’ in last printf()??
The decrement operator has a very important side effect. Namely, that it decreases the value stored by one. Your original array had an ‘r’ in it, but that has been replaced by a ‘q’. After your code runs, the whole array looks like:
The stored values actually changed, so when you reference the fourth element of the array a second time (aka
*ptrora[3]), the value at that location is ‘q’.