xawyzen xawyzen - 1 month ago 9
C Question

Confusion about assigning value to a pointer with offset in C

I was manually assign integer value to a pointer with offset, it appears that

ptr+1
was not actually pointed at
second_int
, or it was because the
printf
function didn't know the size of
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;
}


And the output is:

42
1


Shouldn't it be 42 and 23?

And I found that each time I print the
*(ptr+1)
, it increments by 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;
}


And the output is:

0
1
2
3
4
5
6
7
8
9


What happened?

EDIT:

I'm only allowed to use pointer but not array (doing Learn C the Hard Way excercise). So I manually allocated memory for the
ptr
by
int *ptr = malloc(sizeof(int) * 2);
, then I assign value to
ptr
and
ptr + 1
, and the code run as expected.

Answer

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.