fjiang fjiang - 26 days ago 10
C Question

Different values for array first index and dereferenced pointer to first index

I have the following struct and a function to initialize it (typedef taken from .h and

snake_init()
from .c):

typedef struct snake_t {
size_t len;
int *x, *y;
int *head_x, *head_y;
} Snake;

Snake *snake_init(int x, int y) {
Snake *s = malloc(sizeof(*s) + 2 * sizeof(int));
s->len = 1;

s->x = (int *) (s + 1);
s->y = (int *) (s + 2);
*(s->x) = x;
*(s->y) = y;

s->head_x = s->x;
s->head_y = s->y;
return s;
}


And my main.c (only
int main()
shown):

int main(int argc, char *argv[]) {
Snake *s = snake_init(12, 1234);
// 12 1234
printf("*x: %d *y: %d\n", *(s->x), *(s->y));
// 12 1234
printf("*head_x: %d *head_y: %d\n", *(s->head_x), *(s->head_y));
// 1 1
printf("x == head_x: %d y == head_y: %d", s->x == s->head_x, s->y == s->head_y);
return 0;
}


Even though they point to the same address,
s->y
and
s->head_y
have different values when dereferenced.
s->x
and
s->head_x
don't have this problem. What's wrong with the above code? Does it have something to do with the initialization of
s->x
and
s->y
in
snake_init()
?

Answer
+-------+---+---+
| snake | x | y |
+-------+---+---+
s      s+1

In order to access the ints after "snake" do something like this

int* x = (int *)(s+1);
int* y = (int *)(s+1) + 1;

s->x = x;
s->y = y;
Comments