// ===== CodeLab: C 指针入门 =====
// 来源: https://aoerliang.dpdns.org/articles/c-pointers
// 以下代码片段按文章出现顺序拼接, 共 6 段

// ----- 片段 1 (c) -----
#include <stdio.h>

int main(void) {
    int x = 42;
    printf("x 的值: %d\n", x);
    printf("x 的地址: %p\n", (void *)&x);
    return 0;
}

// ----- 片段 2 (c) -----
#include <stdio.h>

int main(void) {
    int x = 42;
    int *p = &x;      // p 保存 x 的地址
    printf("p 指向的地址: %p\n", (void *)p);
    return 0;
}

// ----- 片段 3 (c) -----
#include <stdio.h>

int main(void) {
    int x = 42;
    int *p = &x;
    printf("解引用 *p = %d\n", *p);   // 42

    *p = 100;        // 通过指针修改 x
    printf("修改后 x = %d\n", x);     // 100
    return 0;
}

// ----- 片段 4 (c) -----
#include <stdio.h>

int main(void) {
    int arr[] = {10, 20, 30};
    int *p = arr;             // 等价于 &arr[0]

    printf("arr[1] = %d\n", arr[1]);
    printf("*(p+1) = %d\n", *(p + 1));   // 也是 20
    printf("p[2] = %d\n", p[2]);         // 30,指针也能用下标
    return 0;
}

// ----- 片段 5 (c) -----
#include <stdio.h>

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 1, y = 2;
    swap(&x, &y);
    printf("x=%d, y=%d\n", x, y);   // x=2, y=1
    return 0;
}

// ----- 片段 6 (c) -----
#include <stdio.h>

int main(void) {
    int *p = NULL;          // 好习惯:先置空
    if (p != NULL) {        // 使用前检查
        printf("%d\n", *p);
    } else {
        printf("指针为空,安全跳过\n");
    }
    return 0;
}
