Question:
Consider the following C code snippet:
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
int x = *ptr++;
int y = *++ptr;
printf("%d %d %d", x, y, *ptr);
What will be the output of this code?
निम्नलिखित C कोड स्निपेट पर विचार करें:
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
int x = *ptr++;
int y = *++ptr;
printf("%d %d %d", x, y, *ptr);
इस कोड का आउटपुट क्या होगा?
Options:
- 10 30 30
- 10 20 20
- 20 30 30
- 10 30 40
- 10 30 30
- 10 20 20
- 20 30 30
- 10 30 40
Correct Answer: a)
Explanation:
Step-by-step trace:
1.
2.
3.
4. At the
Output printed:
1.
ptr initially points to arr[0] (value 10).2.
int x = *ptr++;: Postfix ++ has higher precedence than dereference *, but the increment takes effect after evaluating the current pointer value. So x = *ptr = 10. Then ptr advances to point to arr[1] (value 20).3.
int y = *++ptr;: Prefix ++ increments ptr first, so ptr now points to arr[2] (value 30). Then it dereferences to yield y = 30.4. At the
printf statement, ptr still points to arr[2], so *ptr = 30.Output printed:
10 30 30.
चरणबद्ध विश्लेषण:
1.
2.
3.
4. अंत में
अतः आउटपुट:
1.
ptr शुरू में arr[0] (मान 10) को इंगित करता है।2.
x = *ptr++; में पोस्टफिक्स ++ वर्तमान मान (10) x को देता है और फिर पॉइंटर को arr[1] (20) पर आगे बढ़ाता है।3.
y = *++ptr; में प्रीफिक्स ++ पहले पॉइंटर को arr[2] (30) पर ले जाता है, और फिर मान 30 y में स्टोर होता है।4. अंत में
*ptr का मान भी 30 है।अतः आउटपुट:
10 30 30।