Appendix D: Interview Questions
Common C programming interview questions and model answers.
Appendix D: Interview Questions
Table of Contents
- Table of Contents
- D.1 Basic Questions
- D.2 Intermediate Questions
- D.3 Advanced Questions
- D.4 Exercises
- D.5 Solutions
D.1 Basic Questions
- What is a pointer?
- How do you declare an array in C?
D.2 Intermediate Questions
- What is the difference between
malloc
andcalloc
? - How do you pass a function as a parameter in C?
D.3 Advanced Questions
- Explain undefined behavior with an example.
- What is memory alignment and why is it important?
D.4 Exercises
- Write a function to reverse a string in C.
- What happens if you free the same pointer twice?
D.5 Solutions
D.5.1 Solution 1
A pointer is a variable that stores the address of another variable.
D.5.2 Solution 2
int arr[10];
declares an array of 10 integers.
D.5.3 Solution 3
malloc
allocates uninitialized memory; calloc
allocates zero-initialized memory.
D.5.4 Solution 4
Use a function pointer: void func(void (*fptr)()) { fptr(); }
D.5.5 Solution 5
Undefined behavior: e.g., accessing an array out of bounds. The result is unpredictable.
D.5.6 Solution 6
Memory alignment ensures data is stored at addresses suitable for the hardware, improving performance and avoiding faults.
D.5.7 Solution 7
1
2
3
4
5
6
7
8
void reverse(char *str) {
int n = strlen(str);
for (int i = 0; i < n/2; i++) {
char tmp = str[i];
str[i] = str[n-1-i];
str[n-1-i] = tmp;
}
}
D.5.8 Solution 8
Freeing the same pointer twice causes undefined behavior (often a crash).
This post is licensed under CC BY 4.0 by the author.