Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different way of accessing array elements in C

Tags:

arrays

c

I am a teaching assistant for a C programming course, and I came across the following line of C code:

char str[] = "My cat's name is Wiggles.";
printf("%c %c %c %c\n", str[5], *(str + 5), *(5 + str), 5[str]);

I never came across the very last argument (5[str]) before, and neither did my professor. I don't think it's mentioned in K&R and C Primer Plus. I found this piece of code in a set of technical interview questions. Does anyone know why C allows you to access an array element that way also? I never heard of an index being outside the set of brackets and the name of an array inside the brackets.

Your help will be greatly appreciated!

like image 325
Joe Avatar asked Apr 05 '11 01:04

Joe


4 Answers

It's basically just the way C works. str[5] is really equivelent to *(str + 5). Since str + 5 and 5 + str are the same, this means that you can also do *(5 + str), or 5[str].

It helps if you don't think of "5" as an index, but rather just that addition in C is commutative.

like image 20
Reed Copsey Avatar answered Oct 21 '22 22:10

Reed Copsey


Perfectly valid C. From Wikipedia:

Similarly, 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).

Wacky, but valid.

like image 143
kprobst Avatar answered Oct 21 '22 23:10

kprobst


str[5] directly translates to *(str + 5), and 5[str] directly translates to *(5 + str). Same thing =)

like image 4
Kevin Avatar answered Oct 21 '22 23:10

Kevin


Similarly, 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).

http://en.wikipedia.org/wiki/C_syntax#Accessing_elements

like image 2
Brian Roach Avatar answered Oct 21 '22 22:10

Brian Roach