[] 优先于 * 运算符 [英] [] precedence over * operator

查看:26
本文介绍了[] 优先于 * 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中的某个地方,我做了一些非常糟糕的事情.我的极值变量在运行时出现未定义的行为,但大多数时候它甚至没有运行.任何帮助都会很棒.

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.

推荐答案

出现未定义行为的原因是下标运算符 [] 优先于间接运算符 *.extrema 的值被索引为一个指针数组,这是不正确的,因为那里只有一个指针.

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

ideone 上的演示.

这篇关于[] 优先于 * 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆