Consider the following C program
#include<stdio.h>
int main() {
static int a[] = {10, 20, 30, 40, 50};
static int *p[] = {a, a+3, a+4, a+1, a+2};
int **ptr = p;
ptr++;
printf("%d%d", ptr-p, **ptr);
}
The output of the program is _______.
View worked solution
Answer: 140
Let's trace the execution of the program step-by-step:
- Array
a: An array of 5 integers:a = {10, 20, 30, 40, 50}. - Pointer Array
p: An array of 5 pointers initialized as:p[0] = a(points toa[0], value 10)p[1] = a + 3(points toa[3], value 40)p[2] = a + 4(points toa[4], value 50)p[3] = a + 1(points toa[1], value 20)p[4] = a + 2(points toa[2], value 30)
- Pointer
ptr:- Initially,
ptr = p(points top[0]). - After
ptr++,ptrpoints top[1].
- Initially,
- Evaluating the
printfarguments:ptr - p: Pointer subtraction yields the number of elements between them. Sinceptrpoints top[1]andppoints top[0],ptr - p = 1.**ptr: Dereferencingptronce gives*ptr = p[1] = a + 3. Dereferencing it again gives*(a + 3) = a[3] = 40.
The printf statement prints ptr - p and **ptr consecutively without any spaces: 1 and 40, resulting in 140.
Free practice · Your answers on this page are not saved.
