PointersWhat will be the output of the following C code?main() { static int a[ ] = {0, 1, 2, 3, 4}; int *p[ ] = {a, a+1, a+2, a+3, a+4}; int **ptr = p; ptr++; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr); *ptr++; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr); *++ptr; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr); ++*ptr; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr);}Options1 1 12 2 23 3 33 4 41 1 12 2 23 3 34 4 41 1 12 2 24 4 43 3 31 1 12 2 23 3 33 3 3
Question
PointersWhat will be the output of the following C code?main() { static int a[ ] = {0, 1, 2, 3, 4}; int *p[ ] = {a, a+1, a+2, a+3, a+4}; int **ptr = p; ptr++; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr); *ptr++; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr); *++ptr; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr); ++*ptr; printf("\n %d %d %d", ptr-p, *ptr-a, **ptr);}Options1 1 12 2 23 3 33 4 41 1 12 2 23 3 34 4 41 1 12 2 24 4 43 3 31 1 12 2 23 3 33 3 3
Solution
The output of the given C code will be:
1 1 1 2 2 2 3 3 3 3 4 4
So, the correct option is 1 1 1, 2 2 2, 3 3 3, 3 4 4.
Here's the step by step explanation:
-
ptris a pointer top, which is an array of pointers toa. Initially,ptrpoints top[0]which isa. Whenptris incremented, it points top[1]which isa+1. So,ptr-pis 1,*ptr-ais 1 and**ptris 1. -
*ptr++incrementsptrto point top[2]which isa+2. So,ptr-pis 2,*ptr-ais 2 and**ptris 2. -
*++ptrincrementsptrto point top[3]which isa+3. So,ptr-pis 3,*ptr-ais 3 and**ptris 3. -
++*ptrincrements the value pointed byptrwhich isa[3]from 3 to 4. So,ptr-pis still 3,*ptr-ais 4 and**ptris 4.
Similar Questions
What is the output of the following C code:#include <stdio.h>void fun(int **p);int main(){ int a[3][4] = {1, 2, 3, 4, 4, 3, 2, 8, 7, 8, 9, 0}; int *ptr; ptr = &a[0][0]; fun(&ptr); return 0;}void fun(int **p){ printf("%d\n", **p);}1234
What will be the output of the following C code?void main() { int a[] = {1,2,3,4,5}, *p; p = a; ++*p; printf("%d ", *p);p += 2; printf("%d ", *p);}a.24b.22c.23d.34
What will be the output of the following C code? #include <stdio.h> void main() { int x = 0; int *ptr = &x; printf("%d\n", *ptr); }
What will the following code output?#include <stdio.h>int main() { int arr[3] = {1, 2, 3}; int *p = arr; printf("%d\n", *(p + 2)); return 0;}
What will be the output of the following code?int main() { int *ptr = NULL; ptr = (int*)malloc(sizeof(int)); *ptr = 5; printf("%d\n", *ptr); free(ptr); return 0;}
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.