I need this functionality to pass both dynamically allocated array and idx to a function and assign values to it. Segfault is occuring when I try to allocate value 2 as mentioned in code. What is wrong in this? and how can I resolve it?
#include <stdio.h>
#include <stdlib.h>
void fucn(int *int_ptr, int **arr_ptr)
{
*arr_ptr[*int_ptr] = 1;
(*int_ptr)++;
//*arr_ptr = *arr_ptr + 1;
*arr_ptr[*int_ptr] = 2;
}
int main(int argc, char const *argv[])
{
int *array = calloc(4, sizeof(int));
int i = 0;
fucn(&i, &array);
printf("%d%d", array[0], array[1]);
free(array);
return 0;
}
The problem here is one of operator precedence,
*arr_ptr[i]
is not equivalent to(*arr_ptr)[i]
which is what you really want here, although it would be even better to simply passarray
to your function directly, i.e. make it take a pointer toint
as its second argument, there is no need for the extra level of indirection.So you should have either:
Or: