我有以下结构和一个初始化它的函数(typedef取自.h和snake_init()
来自.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;
}
我的main.c(仅显示int main()
):
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;
}
即使他们指向相同的地址,s->y
和s->head_y
在取消引用时也会有不同的值。 s->x
和s->head_x
没有遇到此问题。上面的代码有什么问题?它是否与s->x
中s->y
和snake_init()
的初始化有关?
答案 0 :(得分:0)
+-------+---+---+
| snake | x | y |
+-------+---+---+
s s+1
为了在“蛇”之后访问整数
int* x = (int *)(s+1);
int* y = (int *)(s+1) + 1;
s->x = x;
s->y = y;