-1

I don't understand when to use the arrow and when to use the point.

For example,

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

Why is the last max with the point and the first two with the arrows? I don't get it. The asterisks and the & are also pretty confusing.

  • 2
    `(*p).x` is the same as `p->x` if `p` is a pointer to a structure with field named `x`. That much of what is needed to know. – Eugene Sh. Jan 30 '19 at 22:04
  • @EugeneSh. Why can't I use the arrow for vect as well? It is a pointer too, isn't it? – user10967362 Jan 30 '19 at 22:06
  • 1
    You can. But `vect` is not a pointer to a single structure, but to an array of these. So you will need to do something like `(vect+i)->media` instead of `vect[i].media`. That would be less readable. (here it worth mentioning that `p[i]` is the same as `*(p+i)` if `p` is a pointer..) – Eugene Sh. Jan 30 '19 at 22:07

2 Answers2

1

Both the arrow and the dot operator are used to access a member of a struct. However, if the struct variable is a pointer, you use an arrow operator, otherwise you use a dot operator.

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;
VHS
  • 9,534
  • 3
  • 19
  • 43
0

The dot operator is used to access members of a struct. However, max is a pointer to a struct. The arrow operator is equivalent to dereferencing the pointer and then using the dot operator. These statements are the same:

max->nome
(*max).media

Ampersands are used to retrieve the address of a variable. Asterisks are used when declaring variables to denote that the declared variable is a pointer, and in expressions to dereference pointers:

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