指针的步长

  • 指针变量+1之后 跳跃的字节数量
  • 解引用的时候,取的字节数

对自定义数据类型进行练习

  • 如果获取自定义数据类型中属性的偏移
  • offsetof(结构体,属性)
  • 头文件#include<stddef.h>

代码示例:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//指针的步长意义
//1、指针变量+1之后 跳跃的字节数量
void test01()
{
   
        char*p = NULL;
        printf("%d\n",p);
        printf("%d\n",p+1);
        double*p2 = NULL;
        printf("%d\n", p2);
        printf("%d\n", p2 + 1);
        printf("%d\n", p2 + 2);
}
//2、解引用时候,取得字节数
void test02()
{
   
        char buf[1024] = {
    0 };
        int a = 1000;
        memcpy(buf + 1, &a, sizeof(int));
        char*p = buf;//通过p找到buf的首地址
        printf("buf中的a=%d\n",*(int*)(p+1));
}
//3、自定义数据类型 练习
struct Person
{
   
        char a;
        int b;
        char buf[64];
        int d;
};
void test03()
{
   
        struct Person p1 = {
   'a',10,"hello world",100};
        //计算结构体中属性的偏移
        printf("p1.d的偏移量为:%d\n",offsetof(struct Person,d));
        //打印d的值
        printf("p1.d的值为:%d\n",*(int*)((char*)&p1+offsetof(struct Person,d)));
}
int main()
{
   
        //test01();
        //test02();
        test03();
        return EXIT_SUCCESS;
}