Advertisement
dmilicev

malloc_array_in_function_and_then_access_array_from_outside.c

Nov 9th, 2023
744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. /*
  2.  
  3.     malloc_array_in_function_and_then_access_array_from_outside.c
  4.  
  5. https://stackoverflow.com/questions/8437791/c-malloc-array-in-function-and-then-access-array-from-outside
  6.  
  7.  
  8.     You can find all my C programs at Dragan Milicev's pastebin:
  9.  
  10.     https://pastebin.com/u/dmilicev
  11.  
  12. */
  13.  
  14. #include<stdio.h>
  15. #include <stdlib.h>
  16.  
  17. // creates a memory location for array arr[n] of n integers
  18. // and fills it with ordinal numbers
  19. void create_array(int **arr, int arr_size) {
  20.     *arr = malloc(sizeof(int) * arr_size);
  21.  
  22.     if (arr == NULL) {  // Check if the memory has been successfully allocated by malloc
  23.         printf("\n Memory not allocated. \n");
  24.         return;
  25.     }
  26.  
  27.     // optionally, we can fill the array of integers with ordinal numbers
  28.     for(int i=0; i<arr_size; i++)
  29.         (*arr)[i] = i+1;
  30. }
  31.  
  32. int main() {
  33.     int *arr, arr_size=10;
  34.  
  35. // create a memory location for array arr[n] of n integers and fills it with ordinal numbers
  36.     create_array(&arr, arr_size);
  37.  
  38.     printf("\n\n");
  39.  
  40.     for (int i=0; i<arr_size; i++)
  41.         printf("%4d", arr[i]);  // arr[i] is the same as *(arr + i)
  42.                                 // so arr[0] is the same as *arr
  43.     printf("\n\n");
  44.  
  45.     free(arr);                  // keep it clean
  46.  
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement