0

Explain the code

ary[-1]

3rd Mar 2020, 5:31 PM
Ajith
Ajith - avatar
3 Answers
0
int ary[3]={1,2,3,4}; int *k=ary +3; Printf("%d",k[-1]);
3rd Mar 2020, 5:33 PM
Ajith
Ajith - avatar
0
pointer arithmetic says that given a pointer p and an integer i, p + i the pointer p advanced by i * sizeof(*p) bytes. which means that the pointer "k" will point to the 3th elem ( in your case k will point to the last elem since ary has a size of 4) . +-----+-----+-----+-----+-----+ | 1 | 2 | 3 | 4 | +-----+-----+-----+-----+-----+ ^ ^ | | ary k == ary + 3 the syntax "array[i]" is equivalent to " *(array + i )". // the compiler converts the array operation in pointers before accessing the array elements. so k[-1] == *(k + -1) == *(k - 1). // k is a pointer to the 3th elem, subtraction of 1 resulted in an address with decrement of 1*sizeof(*k) and by using the dereferencing operator we get the value 3. +-----+-----+-----+-----+-----+ | 1 | 2 | 3 | 4 | +-----+-----+-----+-----+-----+ ^ ^ ^ | | | | | | ary k[-1] ary + 3 == k
3rd Mar 2020, 6:36 PM
MO ELomari
MO ELomari - avatar
0
Thank you
6th Mar 2020, 6:04 AM
Ajith
Ajith - avatar