Consider:
int a[2] = {0,1};
int *address_of_second = (&a[1]);
I assume this works because it’s translated to &*(a+1) and then the & and * cancel each other out, but can I count on it, or is it compiler-specific? That is, does the C standard have anything to say about this?
Is this a decent way to write?
Personally I think that writing:
int *address_of_second = a+1
is better, do you agree?
Thanks.
You can count on the behaviour in your first code example.
a[1]is the same as*(a + 1), and&a[1]is the same as&(*(a + 1)), which gives you a pointer (&) to the (dereferenced,*) int ata + 1. This is well-defined behaviour, which you can count on.This is readable, but not quite as readable as
&a[1]in my opinion.&a[1]explicitly shows thatais a pointer, that you’re referencing an offset of that pointer, and that you’re getting a pointer to that offset.a + 1is slightly more ambiguous in that the actual line doesn’t tell you anything about whatais (you can deduce that it’s a pointer but for all you know from that snippetacould be just anint).Even so, that’s just my opinion. You’re free to make up your own style decisions, so long as you understand that behind the scenes that they’re the same at the lowest level.