首页 > 其他 > 详细

结构体

时间:2018-08-05 19:55:51      阅读:140      评论:0      收藏:0      [点我收藏+]

为什么使用结构体?

1.  在实际工作中,很多数据是有内在联系的,一般是成组出现,如:姓名、性别和年龄等,为了体现它们的内在联系,就需要一个能够存放多种不同类型数据的数据结构。

2.  C语言是面向过程的语言,但是面向对象的思想才更加接近实际,结构体的使用,就好比C++中的类,结构体让面向对象编程的思维可以在C语言中得到应用。

声明一个结构体类型

PS:(不分配内存,就相当于一个数据类型,只有定义了具体变量才分配内存)

struct student //结构体类型为 struct student
{
    char name[64]; //结构体成员
    unsigned char sex;
    int age;
    int number;
};

定义结构体类型变量

1.  先声明结构体类型,再定义结构体类型的变量

#include <stdio.h>
struct student //声明一个结构体类型为 struct student
{
    char name[64];
    unsigned char sex;
    int age;
    int number;
};

int main()
{
    /*定义结构体变量*/
    struct student stu;//类型名 变量名
    printf("the size of struct student is %ld\n", sizeof(stu));
    return 0;
}

运行结果

$ ./a.out 
the size of struct student is 76

PS:输出结果跟我们想象的不太一样,这是因为 4 字节对齐。

2. 在声明类型的同时定义变量

#include <stdio.h>
struct student
{
    char name[64];
    unsigned char sex;
    int age;
    int number;
}stu;//声明时定义

int main()
{
    printf("the size of struct student is %ld\n", sizeof(stu));
    return 0;
}

3.  匿名结构体

#include <stdio.h>
struct //匿名结构体
{
    char name[64];
    unsigned char sex;
    int age;
    int number;
}stu;//不能再用来定义结构体变量

int main()
{
    printf("the size of struct student is %ld\n", sizeof(stu));
    return 0;
}

PS:由于没有结构体名,而类型名是由 “struct 结构体名” 组成,因此不能再用来定义其它变量。

 

结构体

原文:https://www.cnblogs.com/shelmean/p/9426821.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!