fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main()
  5. {
  6.  
  7. // This pointer will hold the
  8. // base address of the block created
  9. int* ptr;
  10. int n, i;
  11.  
  12. // Get the number of elements for the array
  13. printf("Enter number of elements:");
  14. scanf("%d",&n);
  15. //n=70;
  16. printf("Entered number of elements: %d\n", n);
  17.  
  18. // Dynamically allocate memory using malloc()
  19. ptr = (int*)malloc(n * sizeof(int));
  20. ptr[0] = '\0';
  21.  
  22. // Check if the memory has been successfully
  23. // allocated by malloc or not
  24. if (ptr == NULL) {
  25. printf("Memory not allocated.\n");
  26. exit(0);
  27. }
  28. else {
  29.  
  30. // Memory has been successfully allocated
  31. printf("Memory successfully allocated using malloc.\n");
  32.  
  33. // Get the elements of the array
  34. //for (i = 0; i < n; ++i) {
  35. // ptr[i] = i + 1;
  36. //}
  37.  
  38. // Print the elements of the array
  39. printf("The elements of the array are: ");
  40. for (i = 0; i < n; ++i) {
  41. printf("[%d], ", ptr[i]);
  42. }
  43. }
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 5288KB
stdin
5
stdout
Enter number of elements:Entered number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: [0], [0], [0], [0], [0],