0

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)?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
hm1912
  • 314
  • 1
  • 10

3 Answers3

3

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.

pmg
  • 106,608
  • 13
  • 126
  • 198
3

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.


  1. This also means that array indexing is commutative - a[1] == 1[a]. However, you'll rarely see i[a] outside of the International Obfuscated C Code Contest.

John Bode
  • 119,563
  • 19
  • 122
  • 198
0

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.

Community
  • 1
  • 1
Marievi
  • 4,951
  • 1
  • 16
  • 33
  • "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