Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[] precedence over * operator

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.

like image 510
eatonphil Avatar asked Dec 04 '25 11:12

eatonphil


2 Answers

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.

like image 168
Sergey Kalinichenko Avatar answered Dec 06 '25 23:12

Sergey Kalinichenko


a[b] is equal to *(a + b), but has higher precedence than the *. (And like a + b is b + a, so is a[b] equal to b[a]; and 5[a] equal to a[5]).

Thus:

*(extrema)[1] = 90;

// is equal to
*(*(extrema + 1)) = 99;

// When what you want to do is 
*((*extrema) + 1) = 99;

// which is of course equal to
(*extrema)[1] = 99;

However, an even better question is: why are you using the double pointer, when it is not needed.

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,%i\n", arr[0], arr[1]);
}

int main(void)
{
    int *extrema = (int *)malloc(2 * sizeof (int));

    get_extrema(1, extrema);
    print(extrema);

    get_extrema(2, extrema);
    print(extrema);
}


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!