Advertisement
Guest User

Memory allocation

a guest
Oct 22nd, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h> /* required for the malloc and free functions */
  3.  
  4. int main() {
  5.   int number;
  6.   int *ptr;
  7.   int i;
  8.  
  9.   printf("How many ints would you like store? ");
  10.   scanf("%d", &number);
  11.  
  12.   ptr = malloc(number*sizeof(int)); /* allocate memory */
  13.  
  14.  
  15.   if(ptr!=NULL) {
  16.     for(i=0 ; i<number ; i++) {
  17.       *(ptr+i) = i;
  18.     }
  19.  
  20.     for(i=number ; i>0 ; i--) {
  21.       printf("%d\n", *(ptr+(i-1))); /* print out in reverse order */
  22.     }
  23.  
  24.     free(ptr); /* free allocated memory */
  25.     return 0;
  26.   }
  27.   else {
  28.     printf("\nMemory allocation failed - not enough memory.\n");
  29.     return 1;
  30.   }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement