您好,欢迎来到爱够旅游网。
搜索
您的当前位置:首页零基础入门C语言——结构体指针

零基础入门C语言——结构体指针

来源:爱够旅游网

结构体概述

问题定义:有时需要将不同类型的数据组合成一个有机的整体,以便于使用,就类似于sql中的存储一样,随着语言层次的增高封装性是越来越大的。如:

int num;
char name[20];
char sex;
int age;
char addr[30];

成员列表由若干个成员构成,每个成员都是该结构的组成部分,对每个成员必须做类型说明,其形式为:
类型说明符 成员名;
例如说

struct student{
	int num;
	char name[20];
	char sex;
	int age;
	float score;
	char addr[30];
}

可以采用以下三种方法定义结构体类型变量:

  • (1)先声明结构体类型再定义变量名
    例如:struct(类型名) student(结构体) student1(变量名),student2(变量名);
    定义了student1和student2为struct student类型的变量,即他们具有struct student类型的结构

  • (2)在声明类型的同时定义变量这种形式的定义的一般形式为:
    struct 结构体名{
    成员列表
    }变量名;
    例如:

struct student{
	int num;
	char name[20];
	char sex;
	int age;
	float score;
	char addr[30];
}student1,student2

在定义了结构体变量后,系统会为其分配内存单元。例如:
student1和student2在内存中各占几字节?
答(4+20+1+4+4+30 = 63)

  • (3)直接定义结构体类型变量其一般形式为:
    struct{
    成员列表
    }变量名

现在我们直到了怎么构造一个结构体了,下面要说一下在结构体内引用另一个结构体的方法,也就是在结构体内嵌套另一个结构体

struct date{
	int month;
	int day;
	int year;
};
struct {
	int num;
	char name[30];
	char sex;
	struct date birthday;
	float score;
}boy1,boy2;

引用变量法则:
(1)不能将一个结构体变量作为一个整体进行输入和输出。
应该这样引用:

int main() {
    boy1.num = 01;
    boy1.sex = 'M';
    printf("%d,%c", boy1.num, boy1.sex);
}

对于结构体的基础语法说完了,下面来说结构体指针

结构体指针

小案例

struct stu{
    int num;
    char *name;
    char sex;
    float score;
}boy1 = {006,"zhangzhang",'1',69.6};

int main() {

    struct stu *pstu;
    pstu = &boy1;

    printf("%d,%s\n", boy1.num, boy1.name);

    printf("%d,%s\n", (*pstu).num, (*pstu).name);

    printf("%d,%s\n", pstu->num, pstu->name);

}

例题:有一个结构体变量stu,内含学生学号、姓名和三门学科的成绩,通过调用函数print使他们输出

struct student{
    int num;
    char *name;
    int score[3];
};
void print(struct student stu,struct student *pstu){

    printf("num:%d\n",stu.num);
    printf("name:%s\n", stu.name);
    printf("score[0]:%d\n", pstu->score[0]);
    printf("score[1]:%d\n", (*pstu).score[1]);
    printf("score[2]:%d\n", (*pstu).score[2]);
}
int main() {
    struct student *p;
    struct student stu;

    stu.num = 007;
    p->name = "zhangzhang";
    (*p).score[0] = 59;
    (*p).score[1] = 60;
    (*p).score[2] = 61;

    print(stu,p);

//    struct stu *pstu;
//    pstu = &boy1;
//
//    printf("%d,%s\n", boy1.num, boy1.name);
//
//    printf("%d,%s\n", (*pstu).num, (*pstu).name);
//
//    printf("%d,%s\n", pstu->num, pstu->name);



}

动态存储分配

在数组一章中,曾介绍过数组的长度是预先定义好的,在整个程序中固定不变。在C语言中不允许动态数组类型。例如:a[n]就是错误的,必须要用一个实际的数字表示数组长度,但是在实际开发中,往往会发生这种情况,即所需要的内存空间取决于实际输入的数据,而无法预先确定。对于以上问题,使用数组的办法很难解决,只能通过内存管理函数,动态分配内存空间。
常用的内存管理函数有以下三个:
1.分配内存空间函数malloc,calloc
2.释放内存空间函数free

<1>.malloc函数

<2>.calloc函数

<3>.free函数

函数原型是void free(void *p)
其作用是释放由p指向的内存区,使这部分内存区能被其他区使用
p是最近一次调用calloc或者malloc函数的时候返回的值。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igbc.cn 版权所有 湘ICP备2023023988号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务