ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
void swap(int **a, int **b) {
int *temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 1, y = 2;
int *p = &x, *q = &y;
swap(&p, &q);
printf("%d %d", *p, *q);
}- A. Compilation error: swap expects int**
- B. 2 1
- C. 1 2
- D. 0 0
Correct answer: B. 2 1
Passing &p and &q (pointers to the pointers) lets swap actually exchange what p and q themselves point at, by dereferencing a and b once to reach p and q's storage. After swap, p points at y (2) and q points at x (1).
More C Programming questions
- Assume 64-bit LP64, natural alignment. What is printed? c struct A { int i; char c; }; struct B { char c; int i; }; printf("%zu %zu"…
- Assume 64-bit LP64, natural alignment. What is printed? c struct S { double d; int i; }; struct S arr[3]; printf("%zu %zu", sizeof(struct…
- Assume 64-bit LP64. What is printed? c struct Node { int val; struct Node next; }; printf("%zu", sizeof(struct Node));
- Assume 64-bit LP64, natural alignment, and #pragma pack(1) applied. What is printed? c #pragma pack(1) struct Packed { char c; int i; char…
- Assume 64-bit LP64, natural alignment. What is printed? c struct A { int arr[3]; char c; }; printf("%zu", sizeof(struct A));
- What is printed? c int f(int n) { if (n <= 1) return 1; return n f(n - 1); } int main() { printf("%d", f(5)); }