views:

80

answers:

3

If I do *ptr[x], is that equivalent to *(ptr[x]), or (*ptr)[x]?

+6  A: 

*(ptr[x])

See the Wikipedia operator precedence table, or, for a more detailed table, this C/C++ specific table.

Justin Ardini
that link doesn't mention pointer dereferencing... but it does say array access binds most tightly
Claudiu
The `*` is in the 2nd row of the table, after `[]` in the 1st row.
Justin Ardini
Ah, I see how this could be confusing, since `*` could mean multiplication or pointer dereference. Multiplication goes after though, in row 3 of the table.
Justin Ardini
ah yes, reading comprehension for the win. i was scanning the text for mention of the word 'pointer' and didn't realize it's just a unary operation too.
Claudiu
Wikipedia also has a comprehensive C(++)-specific [precedence table](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence).
Matthew Flaschen
@Matthew: Thanks, incorporated this table into my post.
Justin Ardini
Yay, my favorite table. ( http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence )
Nick T
A: 

Using the counter-clockwise movement of analyzing and parsing that simple example

1. starting with ptr, work in counter-clockwise until you hit asterisk operator
2. asterisk, in counter-clockwise until you hit subscript operator
3. we arrive here, at subscript operator [x]

Since [] has higher precedence than the asterisk as per this table , that makes it *(ptr[x])

tommieb75
where does this counterclockwise method come from?
Claudiu
@Claudiu: It's a well known technique for parsing and analyzing C expressions...it is found in 'Expert C Programming - Peter Van der Linden', see http://stackoverflow.com/questions/2305255/pointer-array-syntax-char-p-pn-in-c-c
tommieb75
That's for parsing type specifiers and declarations. But in the question `*ptr[x]` is an expression, and so all you need to know is operator precedence.
Steve Jessop
@Steve: yes, that is how you get to understand which takes precedence...
tommieb75
@Claudiu: http://www.ericgiguere.com/articles/reading-c-declarations.html
tommieb75
So the counter-clockwise thing *doesn't* apply to expressions? I would *strongly* drop mentioning that, as operator precedence is all that matters here.
Nick T
+2  A: 

In C, all postfix operators have higher precedence than prefix operators, and prefix operators have higher precedence than infix operators. So its *(ptr[x])

Chris Dodd