Complete the code to allocate memory for an integer using malloc.
int *ptr = (int *)[1](sizeof(int));The malloc function allocates memory dynamically. Here, it allocates enough space for one integer.
Complete the code to allocate memory for an array of 5 integers.
int *arr = (int *)malloc([1] * sizeof(int));We multiply the number of elements (5) by the size of each element to allocate enough memory for the array.
Fix the error in the code to correctly allocate memory for a float pointer.
float *ptr = (float *)malloc(sizeof([1]));The size should match the type of pointer you want to allocate memory for. Here, it's float.
Fill both blanks to allocate memory for an array of 10 doubles and check if allocation succeeded.
double *arr = (double *)malloc([1] * sizeof([2])); if (arr == NULL) { printf("Memory allocation failed\n"); }
We allocate memory for 10 elements of type double. The first blank is the number of elements, the second is the type.
Fill all three blanks to allocate memory for a char array of 20 elements, initialize it with zeros, and check for success.
char *buffer = (char *)[1](20, sizeof([2])); if (buffer == [3]) { printf("Allocation failed\n"); }
calloc allocates and initializes memory to zero. We allocate 20 chars and check if the pointer is NULL.