Complete the code to declare a pointer for dynamic memory allocation.
int* [1];The pointer ptr is used to hold the address of dynamically allocated memory.
Complete the code to allocate memory dynamically for 10 integers.
ptr = (int*) [1](10 * sizeof(int));
malloc allocates a block of memory of the given size.
Fix the error in the code to properly free the allocated memory.
if (ptr != NULL) { [1](ptr); }
free releases the memory previously allocated by malloc.
Fill both blanks to check if memory allocation failed and handle it.
ptr = (int*) malloc(sizeof(int) * 5); if (ptr [1] NULL) { [2]("Allocation failed!\n"); }
We check if ptr is equal to NULL to detect failure, then print a message.
Fill all three blanks to check if memory allocation failed, print an error if it did, and initialize the array otherwise.
int* ptr = (int*) malloc(sizeof(int) * 10); if (ptr [1] NULL) { [2]("Memory allocation failed!\n"); } else { for (int i = 0; i [3] 10; i++) { ptr[i] = i * i; } }
We check if ptr == NULL to detect allocation failure, print an error if failed, and loop to fill ptr[i] = i * i for i < 10 if successful.