数组第一个索引的不同值和第一个索引的解引用指针

时间:2016-11-06 07:33:40

标签: c

我有以下结构和一个初始化它的函数(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->ys->head_y在取消引用时也会有不同的值。 s->xs->head_x没有遇到此问题。上面的代码有什么问题?它是否与s->xs->ysnake_init()的初始化有关?

1 个答案:

答案 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;