Reputation: 71
#include<stdio.h>
int main()
{
int a[] = {10, 20, 30, 40, 50};
int *b = a - 1;
printf("%d \n",*(a+2));
}
I know that it prints 30
which is same as a[2]
, but how?
What does a - 1
do to the the array a[]
?
Upvotes: 1
Views: 69
Reputation: 141576
a - 1
does not change a
, in the same way that 3 + 2
does not change 3
.
This code causes undefined behaviour because a - 1
tries to form a pointer outside of the bounds of a
. But in practice it is likely that the b
line will just be ignored, so your code will behave the same as:
int a[] = {10, 20, 30, 40, 50};
printf("%d \n",*(a+2));
which of course prints 30
.
Upvotes: 4