Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array arithmetic and pointers [duplicate]

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

I am reading through a tutorial on C and I came across this syntax:

int doses[] = {1, 3, 2, 1000};
doses[3] == *(doses + 3) == *(3 + doses) == 3[doses]

Now the point is to get the int 1000, but the last one doesn't make any sense. Either its late and my brain is not functioning, its something specific to C, or its a typo. I want to cover all my basics when it comes to pointers so reading through it carefully. That means understanding it all. Any answers would be much appreciated!

like image 694
Andy Avatar asked Dec 02 '12 09:12

Andy


2 Answers

From Wikipedia

Since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent to *(i+a), the expression can also be written as i[a], although this form is rarely used.

like image 75
Rotem Avatar answered Oct 20 '22 07:10

Rotem


Yes, array subscripting is commutative in C. e1[e2] is indeed the same as *((e1)+(e2)). But it is useless in production code, and the only purpose of this notation is to make obfuscated source code.

like image 22
md5 Avatar answered Oct 20 '22 07:10

md5