1. Introduction
C interviews frequently test a candidate's understanding of low-level concepts such as memory management, pointers, and storage classes, since these topics reveal how well a candidate understands what is happening 'under the hood' in a program. This guide covers the most commonly asked C interview questions, each explained clearly with the reasoning an interviewer expects to hear. Mastering these concepts will help you confidently answer both theoretical and practical C interview rounds.
Cricket analogy: Just as a fast bowler's true skill is judged by seam position and wrist snap invisible to fans, C interviews probe pointers and memory management to see what's really happening under the hood of a program.
2. Syntax
/* Quick reference to syntax used throughout this Q&A set */
int *p; /* pointer declaration */
int arr[5]; /* array declaration */
malloc(n * sizeof(int)); /* uninitialized heap allocation */
calloc(n, sizeof(int)); /* zero-initialized heap allocation */
static int x; /* static storage class */
const int y = 10; /* read-only variable */
volatile int flag; /* value may change unexpectedly */
#ifndef HEADER_H
#define HEADER_H /* header guard pattern */
#endif3. Explanation
Q: What is the difference between a pointer and an array in C? A: An array name decays into a pointer to its first element in most expressions, but they are not identical. sizeof(arr) gives the total size of the array in bytes, while sizeof(ptr) gives the size of a pointer (typically 8 bytes on 64-bit systems). Arrays allocate fixed, contiguous memory at declaration and cannot be reassigned to point elsewhere, whereas pointers are variables that can be reassigned to point to different memory locations at any time.
Cricket analogy: An array is like a fixed 11-player squad announced before the toss that can't be swapped mid-innings, while a pointer is like a substitute fielder who can be reassigned to cover any position.
Q: What is the difference between malloc() and calloc()? A: Both allocate memory dynamically on the heap, but malloc(size) allocates a single block of 'size' bytes with indeterminate (garbage) initial values, while calloc(n, size) allocates memory for 'n' elements of 'size' bytes each and initializes all bytes to zero. calloc() also internally guards against multiplication overflow, whereas malloc() requires the caller to compute the total size correctly.
Cricket analogy: malloc() is like handing a groundskeeper a patch of pitch without prepping it, leaving unpredictable bounce, while calloc() is like rolling and leveling that same patch first so every ball behaves predictably.
Q: C only supports call by value, so how do we simulate call by reference? A: C passes arguments by value, meaning a function receives a copy of the argument. To let a function modify the caller's original variable, you pass the address of that variable (a pointer) instead. The function then dereferences the pointer to read or modify the original value, effectively simulating pass-by-reference behavior, as seen in functions like scanf("%d", &x) or a swap(int *a, int *b) function.
Cricket analogy: Since C only passes a copy of a value, like handing a scorer a photocopy of the scoresheet they can't officially update, you instead give them the actual scorebook's location so edits like a swapped batting order stick.
Q: What is the difference between a static variable and a global variable? A: A global variable is declared outside any function and has file scope with external linkage by default, meaning it can be accessed from other source files using extern. A static variable declared at file scope has internal linkage, restricting its visibility to the file it's declared in. A static variable declared inside a function retains its value between function calls (unlike a normal local variable) but is only visible within that function.
Cricket analogy: A global variable is like a national team roster visible and editable by any state association via 'extern', while a function-local static is like a bowler's personal wicket tally that persists match to match, hidden from others.
Q: What is structure padding, and why does it happen? A: Structure padding is the insertion of unused bytes between structure members (or after the last member) by the compiler to satisfy each member's memory alignment requirements, which allows the CPU to access data more efficiently. For example, a struct with a char followed by an int may have 3 padding bytes inserted after the char so the int starts at a 4-byte aligned address, making sizeof(struct) larger than the sum of its members' individual sizes.
Cricket analogy: Structure padding is like a team bus leaving gaps between certain players' seats so heavier equipment bags align properly in the aisle, making the bus's total length bigger than just the sum of passengers.
Q: What does the const keyword guarantee, and where can it be placed with pointers? A: const marks a variable as read-only after initialization; any attempt to modify it causes a compile-time error. With pointers, placement matters: 'const int *p' means the data pointed to cannot be modified through p (but p itself can point elsewhere), 'int *const p' means p itself cannot be reassigned (but the data it points to can be modified), and 'const int *const p' means neither the pointer nor the pointed-to data can change.
Cricket analogy: 'const int *p' is like a commentator who can watch the scoreboard but not change it, while switching booths; 'int *const p' is a commentator locked to one booth but free to update that scoreboard; 'const int *const p' is locked to one booth and can't touch the scoreboard at all.
Q: What does the volatile keyword do, and when is it needed? A: volatile tells the compiler that a variable's value may change at any time outside the normal flow of the program (for example, by hardware, an interrupt service routine, or another thread), so the compiler must not optimize away or cache reads/writes to that variable. It is commonly used for memory-mapped hardware registers and variables shared with interrupt handlers.
Cricket analogy: volatile is like telling a scorer never to trust their memory of the score and always re-check the physical scoreboard, because it can change unexpectedly from a DRS review outside the normal over-by-over flow.
Q: Why do header files use include guards like #ifndef/#define/#endif? A: Header guards prevent a header file's contents from being included more than once in the same translation unit, which would otherwise cause 'redefinition' compile errors for types, functions, or macros if the header is directly or indirectly included multiple times (common with nested #include chains). #pragma once achieves the same effect with non-standard but widely supported compiler-specific syntax.
Cricket analogy: Header guards are like a tournament rule ensuring a player can't be registered twice on the same team sheet even if nominated through multiple routes, preventing a 'duplicate player' conflict on match day.
Q: What is a dangling pointer, and how can it be avoided? A: A dangling pointer points to memory that has already been freed or that has gone out of scope (such as returning the address of a local variable from a function). Dereferencing it causes undefined behavior. It can be avoided by setting a pointer to NULL immediately after calling free() on it, and by never returning addresses of automatic (stack) local variables from a function.
Cricket analogy: A dangling pointer is like a fan still cheering for a player's old jersey number after it's been retired and reassigned, or referencing a substitute who already left the ground — set that reference to NULL after they exit.
4. Example
#include <stdio.h>
/* Demonstrates call-by-reference simulation using pointers */
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}5. Output
Before swap: x = 5, y = 10
After swap: x = 10, y = 56. Key Takeaways
- Arrays decay to pointers in expressions but differ in sizeof behavior and reassignability.
- calloc() zero-initializes memory and checks for multiplication overflow; malloc() leaves memory uninitialized.
- Pass-by-pointer is C's mechanism for simulating pass-by-reference, since C is strictly pass-by-value.
- static at function scope preserves a variable's value across calls; static at file scope restricts linkage to that file.
- Structure padding aligns members to natural boundaries, which can make sizeof(struct) larger than the sum of member sizes.
- const restricts modification, volatile prevents compiler optimization on values that can change externally, and header guards prevent duplicate inclusion errors.
Practice what you learned
1. What is the key difference between malloc() and calloc()?
2. How does C simulate pass-by-reference behavior since it is strictly pass-by-value?
3. What does declaring a variable as static inside a function do?
4. What does 'int *const p' mean in terms of const-pointer placement?
5. Why are header guards (#ifndef/#define/#endif) used in C header files?
Was this page helpful?
You May Also Like
Pointers in C
Learn C pointers with syntax, address-of and dereference operators, pointer arithmetic, and common pitfalls, with examples and output.
Dynamic Memory Allocation in C
Master C dynamic memory allocation with malloc, calloc, realloc, and free, including sizing, zero-initialization, and leak prevention.
Structures in C
Understand C structures: syntax, dot vs arrow member access, nested structs, and why sizeof() can exceed the sum of member sizes due to padding.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics