Pointer | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок


Can anyone tell me what does p[-1] mean? int arr[]={-20,-10,0,10,20}; int *p, i; p=arr; for(p=arr+2,i=0;i<3;++i) { printf("%d %d\n",p[-i],p[i]); }

18th Sep 2019, 10:28 AM
1 ответ
+ 5
Remember that an array is actually a pointer to a continuous block of memory. A call like p[ i ] is actually translated into pointer arithmetic *( p + i ). The same goes for a negative index. A call p[ -i ] equals *( p - i ), meaning you access the memory location i steps before where p points to. In your example, p is set to point to the middle of the array, so p[ -1 ] retrieves the location before the third element, which is of course the second element, p[ -2 ] is the first element, and so on.
18th Sep 2019, 10:35 AM
Shadow - avatar