[] precedence over * operator

c, undefined-behavior

Solution

The reason you get undefined behavior is that the subscript operator `[]` takes precedence over the indirection operator `*`. The value of `extrema` is indexed as an array of pointers, which is incorrect, because there's only a single pointer there.

Since you are passing a pointer to a pointer, you need to put the asterisk inside parentheses:

if (quadrant == 1)
{
    (*extrema)[0] = 0;
    (*extrema)[1] = 90;
}
else if (quadrant == 2)
{
    (*extrema)[0] = -90;
    (*extrema)[1] = 0;
}

Demo on ideone.

Problem

Somewhere in my code I am doing something very bad. I'm getting undefined behavior in my extrema variable when it does run but most of the time it doesn't even run. Any help would be really great. ``` #include <stdio.h> void get_extrema(int quadrant, int **extrema) { if (quadrant == 1) { *(extrema)[0] = 0; *(extrema)[1] = 90; } else if (quadrant == 2) { *(extrema)[0] = -90; *(extrema)[1] = 0; } } void print(int* arr) { printf("%i",arr[0]); printf(","); printf("%i\n",arr[1]); } int main(void) { int *extrema = (int*)malloc(2*sizeof(int)); get_extrema(1,&extrema); print(extrema); get_extrema(2,&extrema); print(extrema); } ``` I also tried editing the extrema array using pointer arithmetic like the following: ``` **(extrema) = 0; **(extrema+1) = 90; ``` But that did not work either. I really have no clue where this is going wrong and I could really use some help.

Original source