Data Structures & AlgorithmsHardTCS NQT · Infosys pattern
What is printed? (C: array passed to a function decays to a pointer)
What is printed? (C: array passed to a function decays to a pointer)
void f(int a[]) { printf("%zu ", sizeof(a) / sizeof(a[0])); }
int main(void) {
int a[10];
printf("%zu ", sizeof(a) / sizeof(a[0]));
f(a);
return 0;
} /* 64-bit system: 8-byte pointers, 4-byte int */- A. 10 10
- B. 10 1
- C. 40 8
- D. 10 2
Correct answer: D. 10 2
In main, a is an array of 10 ints: 40 / 4 = 10. A parameter declared int a[] is really int *a, so inside f sizeof(a) is the pointer size 8, giving 8 / 4 = 2. Pass the length separately – the classic array-length bug.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (balanced brackets with a counter only) python def bycounter(s): c = 0 for ch in s: c += 1 if ch == '(' else -1 if c < 0…
- What is printed? (string rotation check) python def isrot(a, b): return len(a) == len(b) and b in a + a print(isrot("waterbottle"…
- What is printed? (sliding window: count subarrays with product less than k, positive values) python def countprod(a, k): if k <= 1: return…
- What is printed? (Java: == vs equals on Strings) java String a = "hello"; String b = "hel" + "lo"; String c = new String("hello"); String…
- What is printed? (expected probes in a hash table) python alpha = 0.75 chaining = 1 + alpha / 2 linearhit = 0.5 (1 + 1 / (1 - alpha))…
- What is printed? (reverse a sublist of a linked list between positions m and n, 1-based) python def revbetween(a, m, n): a = a[:] a[m…