【问题标题】:I don't understand when to use the arrow and when to use the point [duplicate]我不明白何时使用箭头以及何时使用点[重复]
【发布时间】:2019-06-24 07:17:27
【问题描述】:

我不明白什么时候用箭头,什么时候用点。

例如,

void scrivi_file(FILE *output, anagrafe *vect, anagrafe **max, int dim_vect){
    int i;
    *max = malloc(1 * sizeof(anagrafe));
    max[0] = &vect[0];
    for(i=1; i<dim_vect; i++)
        if(vect[i].media > max[0]->media)
            max[0] = &vect[i];
    fprintf(output, "%s %s %f", max[0]->cognome, max[0]->nome, (*max)[0].media);
}

为什么最后一个最大值是点,前两个是箭头?我不明白。星号和 & 也很混乱。

【问题讨论】:

  • (*p).xp-&gt;x 相同,如果 p 是指向具有名为 x 的字段的结构的指针。需要知道的就这么多。
  • @EugeneSh。为什么我也不能将箭头用于 vect?它也是一个指针,不是吗?
  • 你可以。但是vect 不是指向单个结构的指针,而是指向这些结构的数组。所以你需要做类似(vect+i)-&gt;media而不是vect[i].media。那可读性会降低。 (这里值得一提的是,p[i]*(p+i) 相同,如果 p 是一个指针..)

标签: c


【解决方案1】:

点运算符用于访问结构的成员。但是,max 是指向结构的指针。箭头运算符等效于取消引用指针,然后使用点运算符。这些陈述是相同的:

max->nome
(*max).media

和号用于检索变量的地址。声明变量时使用星号表示声明的变量是一个指针,并在表达式中取消引用指针:

int x = 5;
int y;
int * pointer_to_int;
pointer_to_int = &x;
y = *x; // y is now equal to 5

【讨论】:

    【解决方案2】:

    箭头和点运算符都用于访问struct 的成员。但是,如果 struct 变量是指针,则使用箭头运算符,否则使用点运算符。

    struct max {
       int cognome;
       int nome;
       float media;
    }
    
    max a;
    a.cognome = 5;
    a.media = 10.2;
    
    max * b = malloc(sizeof(max));
    b -> cognome = 5;
    b -> media = 10.2;
    //Or if you hate arrows
    (*b).cognome = 5;
    (*b).media = 10.2;
    

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 2020-04-29
      • 2018-07-21
      • 2013-07-27
      • 1970-01-01
      • 2016-04-30
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多