[] precedence over * operator

2019-02-25 01:21发布

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.

2条回答
霸刀☆藐视天下
2楼-- · 2019-02-25 01:47

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);
}
查看更多
Deceive 欺骗
3楼-- · 2019-02-25 01:55

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.

查看更多
登录 后发表回答