zoukankan      html  css  js  c++  java
  • C语言 结构体中的成员域偏移量

    //C语言中结构体中的成员域偏移量
    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    typedef struct _student{
        char name[30];//32
        int num;
    }Student;
    
    
    void main(){
        Student *p = NULL;
        printf("%x
    ", p);//打印 0
        p = p - 1;        
        printf("%x
    ",p);//打印ffffdc
        //说明 指针的加法运算前面已有详述,p - 1移动了 sizeof(Student)个字节
        //由于结构体字节对齐原则,char name[30]数组占据32个字节,不是30个,不明白请看结构体那一章
        //计算出p的步长是 32+4=36
    
        p = p - 2;       
        printf("%x
    ", p);//打印ffff94
    
        p = p + 2;       
        printf("%x
    ", p);//打印ffffdc
        //说明:以上两个的解释同p-1
    
        p = (Student *)1;
        p = p - 1;
        printf("p - 1=%x
    ", p);//打印ffffdd
        p = (Student *)1;
        p = p - p; 
        //警告:警告    1    warning C4047: “=”:“Student *”与“int”的间接级别不同  tec01.c    33    1    C005
        //警告产生原因是p-p得出的值是int型 p是Student *类型
        //由此说明:p - p和p-1有所区别,p-p只是单纯的p的值加减,p-p=0,返回值是int型,而p-1是指针间的运算,返回值是指针
        printf("p - p=%x
    ", p);//打印0
    
        //结构体指针中 . ->操作符本质上是寻址,寻找每一个成员相对于结构体起始位置的内存偏移,
        //该操作在cpu里执行,不会操作内存,所以 p->num等价于  ((Student *)0)->num  因为不会操作内存,所以不会报错
        printf("%x
    ", &(p->num));//打印20   (此处是16进制)
        //说明 &(p->num)是取p->num得地址   num相对于结构体起始位置的内存偏移量是char name[30]  32个字节(结构体字节对齐原则)
        system("pause");
    }

  • 相关阅读:
    Python 面向对象(初级篇)
    python中的运算符
    初识Python
    浅谈计算机
    Zeppelin interperter 模式设置总结图解2
    maven 使用错误
    TensorFlow anaconda命令备忘
    zeppelin ERROR总结
    YARN 命令总结
    Zeppelin interperter 模式设置总结图解1
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5426775.html
Copyright © 2011-2022 走看看