When I have int *integers;
and I allocate memory using
integers = (int *)malloc(sizeof(int) * 10);
, can I access, say the 2nd value stored in there with integers[1]
, or do I have to do that with *(integers + 1)
?

- 165,132
- 21
- 377
- 458

- 314
- 1
- 10
-
Yes. You can. That is the normal way. – Erik Alapää Jan 30 '17 at 13:51
-
Thanks, so is it basically a "dynamic array" when using it that way? – hm1912 Jan 30 '17 at 13:52
-
@Algorithmiker - be wary of the term "dynamic". It has several meanings. Be sure you don't apply the incorrect one here. – StoryTeller - Unslander Monica Jan 30 '17 at 13:58
-
Ther is harld anything useful you can do with **arrays** actually, except take their address, size and alignment. The index-operator for example is applied to a pointer only, not an array. What about pointers in your C book **specifically** is unclear? – too honest for this site Jan 30 '17 at 14:13
3 Answers
Yes, you can access values through pointers as if they were arrays.
In normal circumstances (any use except after &
, sizeof
, or a string literal) an array gets converted to a pointer to its first element, so, in effect, using an array is converted to using a pointer, not the other way round.

- 106,608
- 13
- 126
- 198
-
1You cannot index an array! The array name is converted ot a pointer before the index-operator is applied. – too honest for this site Jan 30 '17 at 14:14
The subscript operator []
is defined in terms of pointer arithmetic. The expression a[i]
is evaluated as *(a + i)
- given the address a
, offset i
elements from that address and dereference the result1.
So, yes, you can use the []
operator on a pointer expression as well as an array expression.
Remember that with pointer arithmetic, the size of the pointed-to type is taken into account - if a
is a pointer to an int
, then a + 1
yields the address of the next integer object (which can be anywhere from 2 to 4 to 8 bytes from a
).
Also remember that arrays are not pointers - an array expression will be converted ("decay") to a pointer expression unless it is the operand of the sizeof
or unary &
operators, or is a string literal used to initialize a character array in a declaration.
- This also means that array indexing is commutative -
a[1] == 1[a]
. However, you'll rarely seei[a]
outside of the International Obfuscated C Code Contest.

- 119,563
- 19
- 122
- 198
can I access, say the 2nd value stored in there with integers1, or do I have to do that with *(integers + 1)?
Yes, you can. Array names decay to pointers so in both cases, you can act as if you have a pointer pointing at the first element of your data.
NOTE : See this link on why you should not cast the result of malloc
.
-
"Array names decay to pointers" - is wrong. They decay **for most usages**. But not always as the statement implies. And it is not "as-if", but they _are_ converted to pointers to the first element. – too honest for this site Jan 30 '17 at 14:40