ProgrammingVery hardProduct company OA
What is printed?
What is printed?
void s1(int *a, int *b) { int *t = a; a = b; b = t; }
void s2(int **a, int **b) { int *t = *a; *a = *b; *b = t; }
int main(void) {
int x = 1, y = 2, *p = &x, *q = &y;
s1(p, q);
printf("%d %d ", *p, *q);
s2(&p, &q);
printf("%d %d %d %d", *p, *q, x, y);
}- A. 1 2 2 1 2 1
- B. 2 1 2 1 1 2
- C. 2 1 1 2 2 1
- D. 1 2 2 1 1 2
Correct answer: D. 1 2 2 1 1 2
s1 swaps its own copies of the pointers and changes nothing for the caller. s2 receives the addresses of p and q and swaps the pointers themselves, so p now points to y and q to x: *p = 2, *q = 1. No int was swapped, so x and y are still 1 and 2.
More C Programming questions
- Why does this fail to compile in C? c void f(int n) { static int k = n; }
- Which line correctly allocates space for a copy of a string pointed to by const char s?
- What is printed? c int a = 3, b = 0; int r = (a > b) + (a && b) 2 + (a || b) 4 + !b 8; printf("%d", r);
- What is printed? c int a[] = {5, 1, 4, 2, 3}; int lo = a, hi = a + 4; while (lo < hi) { if (lo > hi) lo++; else hi--; } printf("%td %d"…
- What is printed? c long memo[50]; int calls = 0; long f(int n) { calls++; if (n < 2) return n; if (memo[n]) return memo[n]; return memo[n]…
- With 4-byte int, what is printed? c int x = 7; printf("%zu %zu", sizeof (int) 3, sizeof x + 1);