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 ?
In C/C++, given a pointer
p
and integral valuek
,p[k]
is evaluated as*(p+k)
. Either form is fine to use as long asp+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:
If you have access to the C++11 standard, see section 5.2.1 Subscripting, Paragraph 1. It says: