C语言结构体

结构体

2016年7月27日 星期三

13:55

结构体是用于保存一组不同类型的数据,结构之间是值传递,相当于拷贝

 

int main(int argc, const char * argv[]) {

 

//    1.定义结构体类型

//    struct 结构体类型名称

//    {

//        

//    }

    struct Person

    {

        char *name ;

        int  age ;

        double height ;

    };

//2.定义结构体变量

    struct Person p;

//3.给结构体变量赋值

    p.name = "lxc";

    p.age  = 23;

    p.height = 178.9;

    return 0;

}

结构体内存储存细节

int main(int argc, const char * argv[]) {

    struct Person

    {

        int age;

        int height;

        int width;

    };

    struct Person p;

    printf("size = %lu\n",sizeof(p));

    printf("&p= %p\n",&p);

    printf("&age = %p\n",&p.age);

    printf("&height = %p\n",&p.height);

    printf("&width = %p\n",&p.width);

    /**

     size = 12

     &p= 0x7fff5fbff7f0

     &age = 0x7fff5fbff7f0

     &height = 0x7fff5fbff7f4

     &width = 0x7fff5fbff7f8

     由以上得出结论,结构体名称并不是结构体的地址

     结构体的地址就是它的第0个属性的地址

     */

    

    return 0;

}

 

结构体是如何分配储存空间

结构体会首先找到所有属性中占用的内存空间最大的那个属性,然后按照该属性的

倍数类分配储存空间。 为什么要这么做,提升计算机的运算速度

例:

#include <stdio.h>

 

int main(int argc, const char * argv[]) {

 //1.找到结构体类型中占用的存储空间最大的属性,以后就按照该属性占用的存储空间来分配

    struct Person2

    {

        double heigth;//8

        int age;//4

    };

    struct Person2 p2;

    printf("p2size = %lu\n",sizeof(p2));

    //p2size = 16

 //2.会从第0个属性开始分配存储,如果存储空间不足就会重新分配,如果存储空间还有剩余,那么就会把后面的属性的数据存储到剩余的存储空间中

    struct Person1

    {

        double height; //8

        int age; //4

        char a; //1

    };

    struct Person1 p1;

    //p2size = 16

    printf("p1size = %lu\n",sizeof(p1));

 //3.会从第0个属性开始分配存储,如果存储空间不足就会重新分配,并且会将当前属性的值,直接存储到新分配的存储空间中,以前剩余的存储空间就不要了

    struct Person

    {

        int age; //4

        double height;//8

        char a;//1

    };

    struct Person p;

    printf("psize = %lu\n",sizeof(p));

    // psize = 24

    return 0;

}

指针指向结构体

int main(int argc, const char * argv[]) {

    //指针指向结构体

    struct Person

    {

        int age;

        char *name;

        double height;

    } p;

    p.age = 30;

    p.name = "lxc";

    p.height = 1.78;

    

    struct Person *personp;

    personp = &p;

    // .运算符的优先级高与*所以要括号括起来

    (*personp).age = 23;

    (*personp).name = "lxx";

    (*personp).height = 1.00;

    

//指针指向结构体的另一种访问形式

    personp->age = 99;

    personp->name = "xxx";

    personp->height = 50;

 

    return 0;

}

结构体指针

struct type

    {

        char *name;

        int age;

        int height;

    };

    struct type types[3] =

    {

        {"a",1},

        {"b",2},

        {"c",3}

    };

    types[0].name = "xx";

    types[1].age = 23;

    types[2].height = 175;

    printf("types[0].name = %s\n types[1].age = %i\n types[2].height = %i\n",types[0].name,types[1].age,types[2].height);

    /**

     types[0].name = xx

     types[1].age = 23

     types[2].height = 175

     */

posted @ 2016-07-29 14:00  偷吃的喵  阅读(192)  评论(0编辑  收藏  举报