What happens if you try to compile and run this program?
What happens if you try to compile and run this program?
#include <stdio.h>
int main (int argc, char *argv[]) {
char *t = "abcdefgh";
char *p = t + 2;
int i;
p++;
p++;
printf("%d ", p[2] – p[-1]);
C++ Institute – CLA-11-03
return 0;
}
Choose the right answer:
A . The program outputs 3
B . The program outputs 4
C . Execution fails
D . The program outputs 2
E . Compilation fails
Answer: A
Explanation:
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 C Certified Associate Programmer Certification, C Essentials 2 – (Intermediate), C Pointers, C Strings
Latest CLA-11-03 Dumps Valid Version with 40 Q&As
Latest And Valid Q&A | Instant Download | Once Fail, Full Refund