0

Are *variable[0] and variable[0][0] the same thing? The first one is a pointer to the first element of an array. And the second one is the first element of an array which is pointed by the first element of the pointed array. Are they pointing to the same element?

5
  • Arrays C++ Tutorails Commented Jul 20, 2017 at 22:21
  • x[y] is interpreted as *(x + y), so yeah, they would be the same thing Commented Jul 20, 2017 at 22:27
  • 1
    This would be a better question if you said what variable was. Commented Jul 20, 2017 at 22:28
  • 1
    As long as type of variable[0] doesn't overload operator [] or operator *, yes. Commented Jul 20, 2017 at 22:31
  • Not sure what do you mean by "And the second one is the first element of an array which is pointed by the first element of the pointed array."? Commented Jul 20, 2017 at 23:01

1 Answer 1

3

According to the C Standard (6.5.2.1 Array subscripting)

2 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 that E1[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 the E2-th element of E1 (counting from zero).

And (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

This expression

variable[0]

yields an array. Applying to it the unary operator * the array is converted to pointer to its first element. So

*variable[0] is equivalent to variable[0][0]

On the other hand according to the first quote the expression

variable[0][0] is equivalent to the expression *( variable[0] + 0 ) that in turn is equivalent to *( variable[0] ) or just *variable[0]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.