Following is the list of some commonly asked questions in C programming language interviews along with their answers and relevant code:
Table of Contents
What is the difference between malloc and calloc?
- malloc: It allocates a specified number of bytes of memory but does not initialize the memory. The initial values are unpredictable.
- calloc: It allocates a specified number of blocks of memory, each of a specified size, and initializes all bytes to zero.
// Example using malloc
int *arr = (int *)malloc(5 * sizeof(int));
// Example using calloc
int *arr = (int *)calloc(5, sizeof(int));
What is a pointer in C?
A pointer is a variable that stores the memory address of another variable. It allows indirect access to the value of the variable it points to.
int x = 10;
int *ptr = &x; // ptr stores the address of variable x
What is the output of the following code?
#include <stdio.h>
int main() {
char str[] = "Hello";
printf("%c\n", str[5]);
return 0;
}
The code tries to access the 6th character of the string “Hello,” which is the null character '\0'
. The output will be an empty line.
What is the difference between ++i and i++?
++i
: Pre-increment increments the value ofi
before using it in an expression.i++
: post-increment increments the value ofi
after using it in an expression.
int i = 5;
int a = ++i; // a = 6, i = 6
int b = i++; // b = 6, i = 7
Explain the concept of recursion. Provide an example.
Recursion is a programming technique where a function calls itself to solve a problem. It requires a base case to terminate the recursion.
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int n = 5;
int result = factorial(n);
printf("Factorial of %d is %d\n", n, result);
return 0;
}
Explain the const keyword in C.
const
is used to define constants or make variables read-only. Aconst
variable cannot be modified once it’s assigned a value.
const int x = 10; // x is a constant with a value of 10
int y = 20;
const int *ptr = &y; // ptr is a pointer to a constant int (can't modify y)
int const *ptr = &y; // Same as above, pointer to a constant int
int *const ptr = &y; // ptr is a constant pointer to int (can't point to another address)
What is the output of the following code?
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
*ptr = 20;
printf("%d\n", x);
return 0;
}
The output will be 20
. *ptr
is dereferencing the pointer and updating the value of x
.
What is the sizeof operator used for?
- The
sizeof
operator returns the size in bytes of a data type or a variable.
int x = 10;
printf("Size of int: %zu\n", sizeof(int));
printf("Size of x: %zu\n", sizeof(x));
Please check Part-B for more question and answers.