Multiple choice technology programming languages

Which one of the following statements allocates enough space to hold an array of 10 integers that are initialized to 0?

  1. int *ptr = (int *) malloc(10, sizeof(int));

  2. int *ptr = (int *) calloc(10, sizeof(int));

  3. int *ptr = (int *) malloc(10*sizeof(int));

  4. int *ptr = (int *) alloc(10*sizeof(int));

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

malloc(10*sizeof(int)) correctly allocates space for 10 integers. Option C is correct - it multiplies the element count by the size of each element. malloc() takes a single byte count argument, while calloc(10, sizeof(int)) initializes to zero but allocates the same size. Option A's malloc(10, sizeof(int)) is incorrect syntax - malloc doesn't take two arguments.

AI explanation

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.