C++, Use [] notation on pointer?

85 views Asked by At

I just noticed I can use [] on a pointer and it works, but I was wondering, if this is good to use it.

int a[]={1,2,3,4};
int *p=&a[1];
std::cout << p[0]; // returns 2;
std::cout << p[-1]; // returns 1;
std::cout << p[1]; // returns 3;

I always learned, you have to use it like this:

std::cout << *(p-1); 
std::cout << *(p+1); 

But is it okay to use the operator [] on a pointer ?

2

There are 2 answers

1
R Sahu On BEST ANSWER

In C/C++, given a pointer p and integral value k, p[k] is evaluated as *(p+k). Either form is fine to use as long as p+k points to valid memory.

If you have access to the C99 Standard, see section 6.5.2.1 Array subscripting, Paragraph 2. It says:

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

If you have access to the C++11 standard, see section 5.2.1 Subscripting, Paragraph 1. It says:

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type. The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2))

0
0x6773 On

In addition to great answer by R Sahu you can also do

std::cout << p[-1]; // returns 1;
std::cout << p[1]; // returns 3;

std::cout << 1[p]; // returns 3;
std::cout << (-1)[p]; // returns 1;

See : Ideone

For pointer p and integer value k :

p[k] and k[p] both are evaluating to *(p+k). So, both are same.

But following one is not same

std::cout << -1[p]; // returns -3;
std::cout << (-1)[p]; // returns 1;