04-数据结构_预备知识-结构体

1, 为什么会出现结构体

    为了表示一些复杂的数据,而普通的基本数据类型无法满足需求.


2, 什么叫结构体

    用户根据实际需要,自定义的复合数据类型
    03-struct.c
    
#include <stdio.h>
#include <string.h> // strcpy(targetStrVar, string)
// 定义结构体
struct Student
{
    int sid;    // 成员
    char name[100]; 
    int age;
};

int main(void)
{
    struct Student st = {123, "张三", 20};
    
    printf("%d, %s, %d\n", st.sid, st.name, st.age);

    st.sid = 456;
    strcpy(st.name, "李四");
    st.age = 22;

    printf("%d, %s, %d\n", st.sid, st.name, st.age);

    return 0;
}


3, 如何使用结构体

    struct Student st = {123, "zhangsan", 20};
    struct Stduent * pSt = &st;
    (1) st.id
    (2) pSt->id  (pSt所指向的结构体变量中的id这个成员)
    03-struct_2.c
#include <stdio.h>
#include <string.h>

struct Student
{
    int id;
    char name[100];
    int age;
};

int main(void)
{
    struct Student st;
    struct Student * pSt;

    pSt = &st;
    
    pSt->id = 123;  // pSt->sid <=> (*pSt).id <=> st.id
    strcpy(pSt->name, "张三");
    pSt->age = 20;

    printf("%d, %s, %d\n", pSt->id, pSt->name, pSt->age);
    
    return 0;
}



4, 注意事项

    (1) 结构体变量之间 只能相互赋值, 不能加减乘除
    (2) 结构体变量 结构体指针变量 作为函数参数的问题.

        03-struct_3.c

#include <stdio.h>
#include <string.h>
// 定义结构体
struct Student
{
    int id;
    char name[100];
    int age;
};

// 给结构体变量赋值
void initStudent(struct Student * pSt) 
{
    pSt->id = 123;
    strcpy(pSt->name, "张三");
    pSt->age = 20;
    return ;
}
// 打印结构体变量, 以结构体变量作为参数
// 慢, 耗费额外的内存(形参), 但安全
void printStudent(struct Student st) 
{   
    printf("%d, %s, %d\n", st.id, st.name, st.age);
    return ;
}
// 打印结构体变量, 以结构体指针变量作为参数,
// 快, 无需分配额外的内存, 
void printStudent_2(struct Student * pSt)
{
    printf("%d, %s, %d\n", pSt->id, pSt->name, pSt->age);
    return;        
}

int main(void)
{
    struct Student st;
    
    initStudent(&st);

    printStudent(st);
    printStudent_2(&st);

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值