Passing dynamic arrays to function in C -



Passing dynamic arrays to function in C -

i trying larn pointers writing simple code snippets. wrote next today,

#include <stdio.h> #include <stdlib.h> void funcall1(int *arr_p, int *num_elements_p) { int = 0; *num_elements_p = 10; int *temp = (int *)malloc(10 * sizeof(int)); if (temp != null) { arr_p = (int *)temp; } else { free(arr_p); printf("error\n"); return; } printf("\n------------------------funcall1------------------------------\n"); (i=0; i<(*num_elements_p); i++) { arr_p[i]= i; printf ("%d\t", arr_p[i]); } } int main() { int *arr = null; int num_elements = 0; int = 0; /*int *temp = (int *)malloc(10 * sizeof(int)); if (temp != null) { arr = (int *)temp; } else { free(arr); printf("error\n"); return; }*/ funcall1(arr, &num_elements); printf("\n------------------------main------------------------------\n"); (i=0; i<num_elements; i++) { printf ("%d\t", arr[i]); } printf ("\n"); free(arr); homecoming 0; }

when utilize malloc in main function code works expected; when utilize in called function doesn't, segmentation fault. have researched bit , understood few basics like, 1. array name pointer first element in array. so, passing parameters correctly. 2. array gets updated, because printing array in called function well.

since arr_p in fact pointing arr points to, when "arr_p = (int *)temp" doesn't mean, arr points allocated memory space? looking happens in memory , why memory access violation here? don't want convince myself partially derived assumptions.

within main, code more or less makes sense.

within funcall1, arr_p copy of value passed it, , if null, attempting free memory has not been allocated.

the function should more like:

void funcall1(int *arr_p, int *num_elements_p) { /* sanity check @ origin of functions */ if (!arr_p || !num_elements_p) { printf("invalid input\n"); return; } int = 0; *num_elements_p = 10; int *temp = (int *)malloc(10 * sizeof(int)); if (temp == null) { printf("memory allocation error!\n"); return; } printf("\n------------------------funcall1------------------------------\n"); (i=0; i<(*num_elements_p); i++) { arr_p[i]= i; printf ("%d\t", arr_p[i]); } }

this appears intended do. also, please refer references below.

references

*function pass value vs. pass reference *, accessed 2014-06-23, <http://courses.washington.edu/css342/zander/css332/passby.html>

c arrays dynamic parameter-passing pass-by-pointer

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -