The program outputs 3 because the expression p[2] - p[-1] evaluates to 3 using the pointer arithmetic rules in C. The pointer t points to the first element of the string literal "abcdefgh", which is stored in a read-only memory location. The pointer p is initialized to t + 2, which means it points to the third element of the string, which is 'c'. Then, p is incremented twice, so it points to the fifth ele-ment of the string, which is 'e'. The subscript operator [] is equivalent to adding an offset to the pointer and dereferencing it, so p[2] is the same as *(p + 2), which is 'g', and p[-1] is the same as *(p - 1), which is 'd'. The printf function then prints the difference between the ASCII values of 'g' and 'd', which is 103 - 100 = 3, as a decimal integer using the %d format specifier.
References = CLA – C Certified Associate Programmer Certification, C Essentials 2 - (Intermediate), C Pointers, C Strings
Contribute your Thoughts:
Chosen Answer:
This is a voting comment (?). You can switch to a simple comment. It is better to Upvote an existing comment if you don't have anything to add.
Submit