[] precedence over * operator

左心房为你撑大大i 提交于 2019-12-20 02:06:54

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/18338966/precedence-over-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!