How to pass a dynamic array to a function in C, along with the index position?

159 Views Asked by At

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;
}
1

There are 1 best solutions below

2
On BEST ANSWER

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 pass array to your function directly, i.e. make it take a pointer to int as its second argument, there is no need for the extra level of indirection.

So you should have either:

void func(int *int_ptr, int **arr_ptr)
{
    (*arr_ptr)[*int_ptr] = 1;

    (*int_ptr)++;

    (*arr_ptr)[*int_ptr] = 2;
}

Or:

void func(int *int_ptr, int *arr_ptr)
{
    arr_ptr[*int_ptr] = 1;

    (*int_ptr)++;

    arr_ptr[*int_ptr] = 2;
}