When accessing an array we use the operator []
like so:
int a[5];
...
a[b] = 12;
What is the proper data type for the variable b
above?
I've found that a[b]
is equivalent to *(a + b)
, which makes me think that I would want b
to be void*
or size_t
but, I'm not sure.
From the C standard(ISO/IEC 9899:TC2) Sec 6.5.2.1 Array subscripting
A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer,E1[E2]
designates theE2-th
element ofE1
(counting from zero).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With