C Programming Interview Questions Set 5
Categories: C Programming language
Ques. What functions are used for dynamic memory allocation in C language?
Ans. malloc()
The malloc() function is used to allocate the memory during the execution of the program.
It does not initialize the memory but carries the garbage value.
It returns a null pointer if it could not be able to allocate the requested space.
Syntax
ptr = (cast-type*) malloc(byte-size) // allocating the memory using malloc() function.
calloc()
The calloc() is same as malloc() function, but the difference only is that it initializes the memory with zero value.
Syntax
ptr = (cast-type*)calloc(n, element-size);// allocating the memory using calloc() function.
realloc()
The realloc() function is used to reallocate the memory to the new size.
If sufficient space is not available in the memory, then the new block is allocated to accommodate the existing data.
Syntax
ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.
In the above syntax, ptr is allocated to a new size.
free():The free() function releases the memory allocated by either calloc() or malloc() function.
Syntax
free(ptr); // memory is released using free() function.
The above syntax releases the memory from a pointer variable ptr.
Ques. What is the difference between malloc() and calloc()?
Ans.calloc()malloc()
DescriptionThe malloc() function allocates a single block of requested memory.The calloc() function allocates multiple blocks of requested memory.
InitializationIt initializes the content of the memory to zero.It does not initialize the content of memory, so it carries the garbage value.
Number of argumentsIt consists of two arguments.It consists of only one argument.
Return valueIt returns a pointer pointing to the allocated memory.It returns a pointer pointing to the allocated memory.
Ques. What is the structure?
Ans. The structure is a user-defined data type that allows storing multiple types of data in a single unit. It occupies the sum of the memory of all members.
The structure members can be accessed only through structure variables.
Structure variables accessing the same structure but the memory allocated for each variable will be different.
Syntax of structure
struct structure_name
{
Member_variable1;
Member_variable2
.
.
}[structure variables];
Let's see a simple example.
#include <stdio.h>
struct student
{
char name[10]; // structure members declaration.
int age;
}s1; //structure variable
int main()
{
printf("Enter the name");
scanf("%s",s1.name);
printf("\n");
printf("Enter the age");
scanf("%d",&s1.age);
printf("\n");
printf("Name and age of a student: %s,%d",s1.name,s1.age);
return 0;
}
Output:
Enter the name shikha
Enter the age 26
Name and age of a student: shikha,26