To answer this question, you need to understand memory allocation in C.
Let's go through each option to understand why it is correct or incorrect:
Option A) int *ptr = (int *) malloc(10, sizeof(int));
This option is incorrect because the malloc
function takes only one argument, which is the number of bytes to allocate. The correct syntax would be malloc(10*sizeof(int))
instead of malloc(10, sizeof(int))
.
Option B) int *ptr = (int *) calloc(10, sizeof(int));
This option is correct. The calloc
function allocates memory for an array of elements and initializes them to zero. It takes two arguments: the number of elements to allocate and the size of each element. In this case, calloc(10, sizeof(int))
allocates enough space for 10 integers and initializes them to 0.
Option C) int *ptr = (int *) malloc(10*sizeof(int));
This option is correct. The malloc
function allocates memory for an array of elements without initializing them. It takes one argument: the number of bytes to allocate. In this case, malloc(10*sizeof(int))
allocates enough space for 10 integers.
Option D) int *ptr = (int *) alloc(10*sizeof(int));
This option is incorrect because there is no standard function called alloc()
in C. The correct function to use for memory allocation is malloc()
.
The correct answer is Option C. This option allocates enough space to hold an array of 10 integers that are initialized to 0.