2

I get segmentation fault when running this but no errors. I am trying to pass pointer to an array of pointers, initialize it as an array of pointers, fill the array and the data available to the calling function.

static void test4(int ***arr)
{
    int *values = (int *) MEM_mallocN(sizeof(int) * 3, "*values");
    values[0] = 0;
    values[1] = 1;
    values[2] = 2;
    *arr = (int **) MEM_mallocN(sizeof(int *) * 3, "*arr");
    *arr[0] = &values[0];
    *arr[1] = &values[1];
    *arr[2] = &values[2];   /* this line causes crash */
}

static void test3(void)
{
    int **arr = NULL;
    test4(&arr);
    for (int i = 0; i < 3; i++) {
        printf("arr[%d] = %p \n", i, arr[i]);
    }
    for (int i = 0; i < 3; i++) {
        printf("arr[%d] = %d \n", i, *arr[i]);
    }
}
  • 4
    `*arr[0]` is `*(arr[0])`, not `(*arr)[0]`. – Ry- Sep 21 '17 at 10:14
  • 2
    There is no apparent reason why you need pointer-to-pointer-to-.... here. Instead of this messy three star programming, you might want to [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). – Lundin Sep 21 '17 at 11:03
  • C has no references. You use a pointer. And being a 3-star programmer is not a compliment. – too honest for this site Sep 21 '17 at 12:24
  • Welcome to Stack Overflow! Please [edit] your question to show us what kind of debugging you've done. I expect you have run your [mcve] within Valgrind or a similar checker, and to have investigated with a debugger such as GDB, for example. Ensure you've enabled a full set of compiler warnings, too. What did the tools tell you, and what information are they missing? And read Eric Lippert's [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Toby Speight Sep 21 '17 at 12:47

1 Answers1

2

It seems you mean

( *arr )[0] = &values[0];
( *arr )[1] = &values[1];
( *arr )[2] = &values[2];   

The postfix subscript operator [] has a higher precedence than the unary operator *.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335