I am trying to learn pointers by writing simple code snippets. I wrote the following today,
#include <stdio.h>
#include <stdlib.h>
void funcall1(int *arr_p, int *num_elements_p)
{
int i = 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");
for (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 i = 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");
for (i=0; i<num_elements; i++)
{
printf ("%d\t", arr[i]);
}
printf ("\n");
free(arr);
return 0;
}
When I use malloc in the main function the code works as expected; but when I use it in the called function it doesn't, I get segmentation fault. I have researched a bit and understood few basics like, 1. Array name is actually a pointer to the first element in the array. So, I am passing the parameters correctly. 2. The array gets updated, because I am printing the array in the called function as well.
Since arr_p is in fact pointing to where arr points to, when I do "arr_p = (int *)temp" doesn't it mean, arr also points to this allocated memory space? I am looking for what happens in the memory and why do I get a memory access violation here? I don't want to convince myself with some partially derived assumptions.