hm1912
hm1912

Reputation: 314

Can I access pointers the same way as arrays?

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

Upvotes: 0

Views: 89

Answers (3)

John Bode
John Bode

Reputation: 123578

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.

Upvotes: 3

pmg
pmg

Reputation: 108986

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.

Upvotes: 3

Marievi
Marievi

Reputation: 5009

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.

Upvotes: 0

Related Questions