I'm playing around with pointers in C, and I can't seem to understand the results I'm getting.
Look at the last iteration & the print statement after the loop, why do I get different values inside and outside the for-loop?
#include <stdio.h>
int main(void)
{
int *ptr;
int a1[] = {2, 5, 4, -1};
ptr = &a1[0];
for (int i = 0; i < 4; i++)
{
printf("######## ITERATION %d ########\n", i);
printf("a1[%d] = %d. \n", i, a1[i]);
printf("Current location - %ld \n", ptr);
ptr = ptr + 1;
printf("Next value would be - a1[%d] = %d at location - %ld\n\n\n", i+1, *ptr, ptr);
}
printf("%ld - %d\n", ptr, *(ptr));
}
And this would be the output -
*** ITERATION 0 ***
a1[0] = 2.
Current location - 2686728
Next value would be - a1[1] = 5 at location - 2686732
*** ITERATION 1 ***
a1[1] = 5.
Current location - 2686732
Next value would be - a1[2] = 4 at location - 2686736
*** ITERATION 2 ***
a1[2] = 4.
Current location - 2686736
Next value would be - a1[3] = -1 at location - 2686740
*** ITERATION 3 ***
a1[3] = -1.
Current location - 2686740
Next value would be - a1[4] = 3 at location - 2686744
2686744 - 4
Look at what I get from the last iteration - The location is 2686744 and the value is 3, and once I make the same print OUTSIDE the for-loop, it has the value 4, for the same address...
This leads to 2 questions -
- Where does that value even come from? There clearly isn't anything after 2686740. That's where the array ends...
- Why does 2686744 have a different value when I print it inside the loop, and outside?
Thanks in advance!