C语言之结构体学习

1. 什么是结构体?

结构体是一种工具,用这个工具可以定义自己的数据类型。

 

2. 结构体与数组的比较

(1) 都由多个元素组成

(2) 各个元素在内存中的存储空间是连续的

(3) 数组中各个元素的数据类型相同,而结构体中的各个元素的数据类型可以不相同

 

3. 结构体的定义和使用

(1)一般形式

struct 结构体名
{
    类型名1 成员名1;
    类型名2 成员名2;
    
    类型名n 成员名n;
};

struct student
{
    char name[10];
    char sex;
    int age;
    float score;
};

(2)定义结构体类型的变量、指针变量和数组

方法一:定义结构体类型时,同时定义该类型的变量

struct [student] /* [ ]表示结构体名是可选的 */
{
    char name[10];
    char sex;
    int age;
    float score;
}stu1, *ps, stu[5]; /* 定义结构体类型的普通变量、指针变量和数组 */

方法二:先定义结构体类型,再定义该类型的变量

struct student
{
    char name[10];
    char sex;
    int age;
    float score;
};
struct student stu1, *ps, stu[5]; /* 定义结构体类型的普通变量、指针变量和数组 */

方法三:用类型定义符typedef先给结构体类型命别名,再用别名定义变量

typedef struct [student]
{
    char name[10];
    char sex;
    int age;
    float score;
}STU;

STU stu1, *ps, stu[5]; /* 用别名定义结构体类型的普通变量、指针变量和数组 */

 

(3) 引用结构体变量中的成员

1) 结构体变量名成员名:      stu1.name

2) 结构体指针变量à成员名:    psàname

3) (*结构体指针变量)成员名: (*ps).name

4) 结构体变量数组名成员名: stu[0].name

 

(4) 示例

#include <stdio.h>
#include <stdlib.h>


typedef struct student
{
char name[10];
char sex;
int age;
float score;
}STU;
STU stu1,*ps,stu[5]; /*用别名定义结构体类型的普通变量、指针变量和数组*/


struct Books
{
char title[50];
int id1;
char author[50];
int id2;
char subject[100];
int id3;
} book = {"C 语言",615452, "RUNOOB",998877, "编程语言", 123456};

//普通变量
void zhangsan()
{
stu1.sex = 1;
stu1.age = 19;
stu1.score = 95.5;
printf("%d\n",stu1.sex);
printf("%d\n",stu1.age);
printf("%.1f\n",stu1.score);
printf("\n");
}

//指针变量
void lisi()
{

/* define 1*/
struct student *p = &stu1;

/* define 2*/
// struct student student1;
// struct student *p = &student1;

p->sex = 0;
p->age = 21;
p->score = 98.5;
printf("%d\n",p->sex);
printf("%d\n",p->age);
printf("%.1f\n",p->score);
printf("\n");
}


//数组
void zeng()
{
stu[0].sex = 1;
stu[0].age = 16;
stu[0].score = 100.5;
printf("%d\n",stu[0].sex);
printf("%d\n",stu[0].age);
printf("%.1f\n",stu[0].score);
printf("\n");
}

//结构体变量的初始化
void struct_const_init()
{
printf("title : %s\nid1: %d\nauthor: %s\nid2: %d\nsubject: %s\nid3: %d\n",
book.title, book.id1, book.author, book.id2, book.subject, book.id3);
}

//测试普通变量、指针变量和数组
void test()
{
STU s1,stu1[5];
STU *p1 = &s1;
s1.sex = 0;
printf("s1.sex: %d\n",s1.sex);
(*p1).sex = 1;
printf("p1->sex: %d\n",(*p1).sex);
stu1[0].sex = 100;
printf("stu1[0].sex: %d\n",stu1[0].sex);
}

int main()
{
zhangsan();
lisi();
zeng();
struct_const_init();
test();
}

 

 

转载博客链接 https://www.cnblogs.com/JCSU/articles/1487302.html

posted @ 2020-07-07 09:15  K_Code  阅读(202)  评论(0编辑  收藏  举报