Interview Questions and Answers on C (2025)
Top Interview Questions and Answers on C ( 2025 )
1. What is the difference between malloc() and calloc() in C?
Answer:
Both malloc() and calloc() are used for memory allocation in C, but there are key differences:
· malloc(): Stands for "memory allocation". It allocates a block of memory of a specified size but does not initialize it, meaning the values stored in the allocated memory are undefined.
· int *ptr = (int*)malloc(5 * sizeof(int)); // Allocates memory for 5 integers.
· calloc(): Stands for "contiguous allocation". It allocates memory for an array of elements and initializes the memory to zero.
· int *ptr = (int*)calloc(5, sizeof(int)); // Allocates memory for 5 integers and sets them to 0.
Key Difference: malloc() doesn’t initialize memory, while calloc() initializes the memory to zero.
2. What are pointers in C?
Answer:
A pointer in C is a variable that stores the memory address of another variable. Pointers are powerful tools in C, allowing direct memory manipulation and helping to increase the efficiency of the program.
· Example:
· int a = 10;
· int *ptr = &a; // ptr stores the address of the variable a
Pointers are essential for dynamic memory allocation, handling arrays and strings, and working with functions more efficiently (e.g., passing by reference).
3. What is the difference between == and = in C?
Answer:
In C programming:
· = is the assignment operator, used to assign a value to a variable.
· int x = 10; // assigns 10 to x
· == is the equality operator, used to compare two values.
· if (x == 10) {
· // code to execute if x is equal to 10
· }
Important: Using = instead of == in conditional expressions (like if) is a common programming mistake.
4. What are the different types of storage classes in C?
Answer:
In C, there are four types of storage classes that determine the lifetime, visibility, and scope of variables:
1.auto: Default storage class for local variables. These variables are automatically created when the block is entered and destroyed when the block is exited.
2.register: Used to hint to the compiler that the variable should be stored in a CPU register for faster access.
3. static: Retains the value of the variable between function calls, preserving its state.
4. extern: Used to declare variables that are defined outside the current file (i.e., global variables in other files).
5. What is recursion in C?
Answer:
Recursion is a technique in C (and many other programming languages) where a function calls itself in order to solve smaller instances of the same problem. It consists of two main parts:
· Base case: A condition that stops the recursion.
· Recursive case: The part where the function calls itself with a modified argument.
Example: Factorial of a number using recursion:
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
6. What is the use of the const keyword in C?
Answer:
The const keyword in C is used to declare variables whose values cannot be modified after initialization. It provides a way to make data read-only, improving code safety and clarity.
· Example:
· const int x = 5; // x cannot be changed
Usage scenarios:
· Protecting sensitive data.
· Indicating that a function parameter should not be modified.
7. What is the difference between ++i and i++ in C?
Answer:
Both ++i (pre-increment) and i++ (post-increment) increment the value of i by 1, but they differ in when the increment happens in the expression:
· ++i: The value of i is incremented before it is used in the expression.
· int i = 5;
· int result = ++i; // i is incremented to 6, then assigned to result.
· i++: The value of i is incremented after it is used in the expression.
· int i = 5;
· int result = i++; // result gets 5, then i is incremented to 6.
8. What is a linked list in C?
Answer:
A linked list is a linear data structure where elements (nodes) are stored in memory. Each node contains two parts:
·Data: The actual data of the node.
·Pointer: A reference (address) to the next node in the list.
Types of Linked Lists:
1.Singly Linked List: Each node points to the next node.
2.Doubly Linked List: Each node points to both the next and the previous node.
3.Circular Linked List: The last node points back to the first node.
Example of a simple singly linked list node structure:
struct Node {
int data;
struct Node* next;
};
9. What is a memory leak in C?
Answer:
A memory leak occurs when dynamically allocated memory is not properly deallocated using free(), resulting in wasted memory resources. This can lead to performance issues and even program crashes over time.
To avoid memory leaks, always ensure that free() is called after the memory allocation is no longer needed:
int *ptr = (int*)malloc(10 * sizeof(int));
// After use
free(ptr); // Deallocate memory
10. What are function pointers in C?
Answer:
A function pointer is a pointer that points to a function instead of a variable. It allows you to dynamically call functions and pass functions as arguments to other functions.
Example:
#include <stdio.h>
void hello() {
printf("Hello, World!\n");
}
int main() {
void (*ptr)(); // Declare a function pointer
ptr = hello; // Assign the function address to the pointer
ptr(); // Call the function using the pointer
return 0;
}
Use case: Function pointers are used in callback functions and implementing function tables.
Conclusion:
These C programming interview questions and answers cover fundamental concepts and common interview topics that candidates may encounter. Mastering these key concepts will give you a solid foundation for acing C programming interviews.
Top Interview Questions and Answers on C ( 2025 )
Some C interview questions, along with their explanations and example answers. This covers a range of topics, from basics to more advanced concepts.
1. What is the difference between ++i and i++ in C?
Answer: Both ++i and i++ are increment operators, but they differ in their behavior:
++i is pre-increment. It increments the value of i and then uses it.
i++ is post-increment. It uses the current value of i and then increments it.
Example:
int i = 5;
int a = ++i; // a = 6, i = 6
int b = i++; // b = 6, i = 7
2. What is a pointer in C?
Answer: A pointer is a variable that stores the memory address of another variable. It allows for indirect access to the value stored in another variable.
Example:
int x = 10;
int *p = &x; // p holds the address of x
printf("Value of x: %d\n", *p); // Dereferencing p to get the value of x
3. What is a NULL pointer?
Answer: A NULL pointer is a pointer that doesn’t point to any valid memory location. It is often used to indicate that the pointer is not initialized or doesn't point to any valid object.
Example:
int *ptr = NULL; // NULL pointer
if (ptr == NULL) {
printf("Pointer is NULL\n");
}
4. Explain the difference between malloc() and calloc() in C.
Answer:
malloc() (memory allocation) allocates a specified number of bytes of memory but does not initialize the memory. The initial values are undetermined.
calloc() (contiguous allocation) allocates memory for an array of specified elements and initializes all bits to zero.
Example:
int *arr1 = (int*)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
int *arr2 = (int*)calloc(5, sizeof(int)); // Allocates and initializes memory for 5 integers to 0
5. What is the purpose of free() in C?
Answer: free() is used to deallocate memory that was previously allocated by functions like malloc(), calloc(), or realloc(). It prevents memory leaks by releasing memory back to the heap.
Example:
int *ptr = (int*)malloc(10 * sizeof(int)); // Allocate memory
free(ptr); // Free the allocated memory
6. What is a structure in C?
Answer: A structure in C is a user-defined data type that allows grouping of different types of variables (members) under a single name.
Example:
struct Person {
char name[50];
int age;
};
struct Person person1;
person1.age = 30;
strcpy(person1.name, "John");
7. What is the use of typedef in C?
Answer: typedef is used to create a new name (alias) for an existing data type. It improves code readability and allows for abstraction.
Example:
typedef unsigned int uint;
uint x = 10; // x is now of type unsigned int
8. Explain the difference between break and continue statements in C.
Answer:
break is used to terminate a loop or switch statement prematurely.
continue is used to skip the current iteration of the loop and move to the next iteration.
Example:
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // Skip when i equals 3
}
printf("%d ", i); // Prints 0 1 2 4
}
9. What is the difference between == and = in C?
Answer:
== is the equality operator, used to compare two values.
= is the assignment operator, used to assign a value to a variable.
Example:
int a = 5; // Assignment
if (a == 5) { // Equality check
printf("a is 5\n");
}
10. What are the different storage classes in C?
Answer: In C, there are four storage classes:
auto: Default storage class for local variables.
register: Suggests that the variable be stored in a CPU register for faster access.
static: Preserves the value of a variable between function calls.
extern: Declares a variable that is defined outside the current function or file.
Example:
static int counter = 0; // Retains value between function calls
extern int x; // Defined elsewhere in the program
11. What is the use of the sizeof() operator in C?
Answer: The sizeof() operator returns the size (in bytes) of a data type or object.
Example:
int x = 10;
printf("Size of x: %zu bytes\n", sizeof(x)); // Output will be the size of an int
12. What is the purpose of the goto statement in C?
Answer: The goto statement is used to transfer control to a different part of the program. It is generally discouraged as it makes code harder to follow and maintain.
Example:
int x = 5;
if (x > 3) {
goto label; // Jump to label
}
label:
printf("x is greater than 3\n");
13. Explain what happens when you divide an integer by zero in C.
Answer: Dividing an integer by zero results in undefined behavior. In most cases, it will cause a runtime error or the program may crash.
Example:
int a = 5;
int b = 0;
int result = a / b; // Undefined behavior, division by zero
14. What is the difference between strcpy() and strncpy() in C?
Answer:
strcpy() copies a string to another string, and it does not check for buffer overflow.
strncpy() copies a specified number of characters and ensures that no more than the given number of characters are copied.
Example:
char dest[10];
strcpy(dest, "Hello"); // Copies "Hello" to dest
strncpy(dest, "HelloWorld", 5); // Copies only "Hello" to dest
15. What is a segmentation fault?
Answer: A segmentation fault (segfault) occurs when a program attempts to access a memory location that it's not allowed to. Common causes include dereferencing NULL pointers, accessing out-of-bounds arrays, or improper memory management.
Example:
int *ptr = NULL;
*ptr = 10; // Dereferencing a NULL pointer causes a segmentation fault
16. What are enum types in C?
Answer: An enum (enumeration) is a user-defined data type that consists of integral constants, making the code more readable.
Example:
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Day today = Wednesday;
17. What is the difference between struct and union in C?
Answer:
A struct is a collection of variables of different data types, each of which has its own memory location.
A union is a collection of variables of different data types, but all members share the same memory location, meaning only one member can hold a value at any given time.
Example:
struct Student {
int age;
char name[50];
};
union Data {
int intValue;
char charValue;
};
These questions and answers cover essential C programming concepts and should help in preparing for C programming interviews.
Advance Interview Questions and Answers on C (2025)
1. What is the difference between struct and union in C?
Answer:
In C, both struct and union are used to store multiple variables of different data types in a single unit, but they differ significantly in terms of memory allocation and usage.
· struct:
o Each member of a struct is allocated its own memory space, meaning the size of a struct is the sum of the sizes of its members.
o Members can have different data types, and they are stored independently.
o Example:
o struct Person {
o char name[20];
o int age;
o };
· union:
o A union uses the same memory space for all its members, meaning all members share the same memory location.
o The size of a union is determined by the size of its largest member.
o Example:
o union Data {
o int intVal;
o float floatVal;
o char charVal;
o };
Key Difference: In a struct, all members are stored at different memory locations, whereas in a union, all members share the same memory location.
2. Explain the concept of Dangling Pointers in C and how to avoid them.
Answer:
A dangling pointer is a pointer that continues to reference a memory location that has been deallocated or is no longer valid. This is a common issue in C programming, especially when using free() to deallocate memory dynamically allocated using malloc() or calloc().
Example of a Dangling Pointer:
int *ptr = (int*)malloc(sizeof(int));
*ptr = 5;
free(ptr); // Memory is freed
// Now ptr is a dangling pointer, as the memory has been deallocated
How to Avoid Dangling Pointers:
1. Set the pointer to NULL after freeing memory:
2. free(ptr);
3. ptr = NULL; // Avoids dangling pointer
4. Avoid using free() on pointers that have already been freed.
5. Use tools like valgrind or AddressSanitizer to detect memory issues in your program.
3. What is the purpose of volatile keyword in C?
Answer:
The volatile keyword in C is used to tell the compiler not to optimize the variable, as its value may be modified externally, such as by hardware or an interrupt service routine.
Use Cases for volatile:
· Accessing hardware registers in embedded systems programming.
· Variables shared between an ISR (Interrupt Service Routine) and the main program.
Example:
volatile int interruptFlag; // Tells compiler not to optimize this variable
Without volatile, the compiler might optimize the reading of interruptFlag and skip the check, assuming it never changes.
4. What are the advantages of using const with pointers in C?
Answer:
The const keyword is used in C to make a variable immutable. When combined with pointers, const can be used in several ways to enhance code clarity and safety.
Types of const with pointers:
1. Pointer to a constant:
o The data being pointed to cannot be modified, but the pointer can be redirected to another memory location.
2. const int *ptr; // You can't change the value of *ptr, but can change ptr to point to another location
3.Constant pointer:
o The pointer itself is constant and cannot point to a different memory location, but the data it points to can be modified.
4. int * const ptr; // ptr always points to the same location, but *ptr can be changed
5. Constant pointer to a constant:
o Neither the data nor the pointer can be modified.
6. const int * const ptr; // Both the data and the pointer are constant
Advantages:
· It helps prevent accidental modification of critical data.
· Enhances code readability by making intentions clear.
· Provides better optimization opportunities for the compiler.
5. What is the difference between stack and heap memory in C?
Answer:
In C, memory is divided into several regions, with the stack and heap being two of the most commonly used for dynamic memory allocation.
· Stack Memory:
o Automatically allocated and deallocated.
o Used for local variables and function calls.
o Memory is organized in a last-in-first-out (LIFO) manner.
o Fast access but limited in size (can lead to stack overflow).
o Example: Local variables in a function.
· Heap Memory:
o Dynamically allocated using functions like malloc(), calloc(), or realloc().
o Memory must be manually deallocated using free().
o Larger but slower compared to the stack and is prone to memory leaks if not properly managed.
Key Difference: Stack memory is temporary and limited, whereas heap memory is more flexible but requires manual management.
6. What is a Segmentation Fault in C, and how can you prevent it?
Answer:
A Segmentation Fault (Segfault) is a runtime error that occurs when a program tries to access memory that it is not allowed to, such as accessing an invalid memory address or dereferencing a null or uninitialized pointer.
Common Causes of Segmentation Faults:
1. Dereferencing null pointers:
2. int *ptr = NULL;
3. *ptr = 5; // Causes segmentation fault
4. Accessing array elements out of bounds:
5. int arr[5];
6. arr[10] = 5; // Causes segmentation fault (out of bounds)
7. Accessing freed memory (dangling pointers):
8. free(ptr);
9. *ptr = 10; // Causes segmentation fault
How to Prevent Segmentation Faults:
· Always initialize pointers to NULL before using them.
· Check for valid memory addresses before dereferencing pointers.
· Use bounds checking when working with arrays.
· Employ tools like gdb, valgrind, and AddressSanitizer for debugging.
7. What is the significance of #define in C?
Answer:
In C, the #define directive is used for defining macros or constants. It is part of the preprocessor, which performs substitution before the compilation process begins.
Common Uses of #define:
1. Constant values:
2. #define PI 3.14159 // Defining a constant value
3. Macro functions:
4. #define SQUARE(x) ((x) * (x)) // Defining a macro function
5. Conditional Compilation:
6. #define DEBUG 1
7. #if DEBUG
8. printf("Debugging information\n");
9. #endif
Advantages:
· #define allows for easier code maintenance (changing a value in one place).
· Increases readability by giving descriptive names to constants.
8. What is the purpose of inline functions in C?
Answer:
The inline keyword in C is used to suggest that the compiler should replace the function call with the function's actual code to reduce function call overhead. It can be particularly useful for small, frequently called functions.
Example:
inline int add(int a, int b) {
return a + b;
}
Advantages of inline Functions:
· Reduces the overhead of function calls, especially in performance-critical code.
· Can improve performance by avoiding the cost of pushing arguments to the stack and jumping to function code.
Note: The compiler may choose to ignore the inline suggestion if it determines that inlining the function would not be beneficial.
Conclusion:
These advanced C programming questions and answers delve into more complex concepts and provide insights into the intricacies of memory management, optimization, and safe coding practices. Understanding these concepts is crucial for candidates aiming to excel in C programming interviews and improve their problem-solving skills in real-world projects.
C interview questions and answers
C programming interview questions
C language interview questions
C interview questions for freshers
C interview questions for experienced
Technical interview questions on C
C programming questions with answers
Advanced C interview questions
Frequently asked C interview questions
C data structures interview questions
C pointers interview questions
Best C interview questions and answers PDF
What are the most asked C interview questions?
C language interview questions and answers for freshers
Real-time C programming interview questions
Interview questions on C for software developer
C language interview tips for freshers
How to crack C language interview?
Top 50 C Interview Questions and Answers
C Programming Interview Questions for Freshers and Experienced
Master C Interviews: Most Asked Questions with Detailed Answers
Comments
Post a Comment