/* Example: dynamic memory allocation for array in C language */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <stdbool.h> #include <errno.h> #include <unistd.h>? int main() { // Used to save the base address of the created memory block int* ptr; int n, i; // Get the size of the array from the user printf("Please enter the number of array elements:"); scanf("%d",&n); printf("The number of elements is: %d\n", n); // Use malloc () function to dynamically allocate memory ptr = (int*)malloc(n * sizeof(int)); // Check whether malloc has successfully allocated memory if (ptr == NULL) { printf("Memory not allocated successfully.\n"); exit(0); } else { printf("Memory allocated successfully.\n"); // Set array elements for (i = 0; i < n; ++i) { ptr[i] = i + 1; } // print array elements printf("elements: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
output:
Please enter the number of array elements:8 The number of elements is: 8 Memory allocated successfully. elements: 1, 2, 3, 4, 5, 6, 7, 8, Process returned 0 (0x0) execution time : 9.076 s