I was manually assign integer value to a pointer with offset, it appears that
ptr+1
second_int
printf
ptr+1
#include <stdio.h>
int main(void)
{
int first_int = 42;
int second_int = 23;
int *ptr = &first_int;
*(ptr + 1) = second_int;
int i = 0;
for (i = 0; i < 2; i++) {
printf("%d\n", *(ptr+i));
}
return 0;
}
42
1
*(ptr+1)
#include <stdio.h>
int main(void)
{
int first_int = 42;
int second_int = 23;
int *ptr = &first_int;
*(ptr + 1) = second_int;
int i = 0;
for (i = 0; i < 10; i++) {
printf("%d\n", *(ptr+1));
}
return 0;
}
0
1
2
3
4
5
6
7
8
9
ptr
int *ptr = malloc(sizeof(int) * 2);
ptr
ptr + 1
In your code, ptr+1
is not memory managed by you.
It could be used by another program, or for any part or your program. What happens here is that the compiler optimizes away the second_int
, as only its value is used. So no memory is allocated for it.
The next int in memory is fortunately also managed by you, and it is the index of your loop.
You thought memory layout was like this:
first_int | second_int | i
But it's like so:
first_int | i
If you want to be able to refer to both int with a pointer + offset, then you have to declare them as an array, to make sure that they are contiguous in memory:
int my_ints[2] = { 42, 0};
int *ptr = my_ints;
*(ptr+1) = second_int;
Then your code will work as intended.