Interview Questions
Arrays · Study material
C Arrays Interview Questions and Answers
1. What is an array, and how is it stored?
A fixed number of elements of one type in one contiguous block of memory. Element i is at base + i × sizeof(element), which makes indexing O(1).
2. What is array decay?
In most expressions an array is converted to a pointer to its first element. It does not happen for sizeof a, &a or a string literal initialising a char array.
3. What is the difference between a, &a[0] and &a?
All hold the same address. a (after decay) and &a[0] are int *; &a is a pointer to the whole array, int (*)[N], so &a + 1 skips the entire array.
4. Why can't you find an array's length inside a function?
The function receives only a pointer, so sizeof measures the pointer. Pass the length as a parameter.
5. Can you assign one array to another?
No, an array is not a modifiable lvalue. Copy element by element or with memcpy(). An array inside a struct, however, is copied when the struct is assigned.
6. What are designated initializers?
A C99 feature that sets chosen elements by index: int a[10] = {[3] = 1, [7] = 2};. Elements not named are 0.
7. What is a variable length array, and when should you avoid it?
An array whose size is decided at run time, stored on the stack. Avoid it for large or untrusted sizes, since a big VLA can overflow the stack; use malloc() instead. VLAs are optional since C11.
8. How is a 2D array laid out in memory?
Row-major: all of row 0, then row 1, and so on. That is why functions must know the column count: void f(int m[][COLS]).
9. What happens if you access a[10] in a 10-element array?
Undefined behaviour. C does no bounds checking; the program may read garbage, corrupt other variables or crash.
10. Is i[a] valid?
Yes. a[i] is defined as *(a + i) and addition commutes, so i[a] is *(i + a) – legal, though never good style.
11. What does int a[static 10] in a parameter mean?
The caller promises to pass a non-null pointer to at least 10 elements. Compilers can warn when you pass less and may optimise using the promise.
12. What does C23 change for arrays?
The empty initializer = {} zeroes an array (even a VLA), constexpr constants can size arrays, and typeof copies an array's type.