Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- malloc_array_in_function_and_then_access_array_from_outside.c
- https://stackoverflow.com/questions/8437791/c-malloc-array-in-function-and-then-access-array-from-outside
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include<stdio.h>
- #include <stdlib.h>
- // creates a memory location for array arr[n] of n integers
- // and fills it with ordinal numbers
- void create_array(int **arr, int arr_size) {
- *arr = malloc(sizeof(int) * arr_size);
- if (arr == NULL) { // Check if the memory has been successfully allocated by malloc
- printf("\n Memory not allocated. \n");
- return;
- }
- // optionally, we can fill the array of integers with ordinal numbers
- for(int i=0; i<arr_size; i++)
- (*arr)[i] = i+1;
- }
- int main() {
- int *arr, arr_size=10;
- // create a memory location for array arr[n] of n integers and fills it with ordinal numbers
- create_array(&arr, arr_size);
- printf("\n\n");
- for (int i=0; i<arr_size; i++)
- printf("%4d", arr[i]); // arr[i] is the same as *(arr + i)
- // so arr[0] is the same as *arr
- printf("\n\n");
- free(arr); // keep it clean
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement