Complete the code to allocate memory dynamically for an integer.
#include <stdlib.h> int main() { int *ptr = (int*)[1](sizeof(int)); if (ptr == NULL) { return 1; } *ptr = 10; free(ptr); return 0; }
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 dynamically.
#include <stdlib.h> int main() { int *arr = (int*)malloc([1] * sizeof(int)); if (arr == NULL) { return 1; } free(arr); return 0; }
We multiply the number of elements (5) by the size of each integer to allocate enough memory for the array.
Fix the error in the code to properly allocate and free memory for a float variable.
#include <stdlib.h> int main() { float *ptr = (float*)[1](sizeof(float)); if (ptr == NULL) { return 1; } *ptr = 3.14f; free(ptr); return 0; }
The malloc function is used to allocate memory. Using free here is incorrect because it deallocates memory.
Fill both blanks to allocate memory for 10 doubles and check if allocation was successful.
#include <stdlib.h> #include <stdio.h> int main() { double *data = (double*)[1](10 * sizeof(double)); if (data [2] NULL) { printf("Allocation failed\n"); return 1; } free(data); return 0; }
malloc allocates memory. We check if the pointer is not equal to NULL to confirm successful allocation.
Fill all three blanks to create a dynamic array of chars, assign a value, and free the memory.
#include <stdlib.h> #include <stdio.h> int main() { char *buffer = (char*)[1](20 * sizeof(char)); if (buffer == NULL) { return 1; } buffer[0] = [2]; printf("First char: %c\n", buffer[0]); [3](buffer); return 0; }
We use malloc to allocate memory, assign the character 'A' to the first element, and then free the memory with free.