【C/C++ 学习笔记】结构体

【C/C++ 学习笔记】结构体

视频地址: Bilibili

结构体定义

语法:struct 结构体名 { 结构体成员列表 }

c++ 复制代码
struct Student {
    string name;
    int age;
    int score;
}

int main() {
    struct Student stu1 = {
        'heyq',
        19,
        100
    };
}

结构体数组

struct 结构体名 数组名元素格式 = { {}, {}, {}, ... };

c++ 复制代码
struct Student students[1] = {
    {
        '1',
        1,
        9
    },
    {
        '2',
        2,
        100
    }
};

结构体指针

利用操作符 -> 可以通过结构体指针访问结构体属性

c++ 复制代码
struct Student {
    string name;
    int age;
    int score;
}

int main() {

    // 创建结构体变量
    struct Student stu1 = { 'heyq', 18, 100 };

    // 创建结构体指针
    struct Student *p = &stu1;

    // 访问成员变量
    cout << p->name << endl;

    return 0;
}

结构体嵌套结构体

c++ 复制代码
struct Student {
    string name;
    int age;
    int score;
}

struct Teacher {
    string name;
    int age;
    struct Student *students;
}

结构体传参

  • 值传递
c++ 复制代码
#include <iostream>
#include <string>

using namespace std;

struct Student {
    string name;
}

void printStudent1(struct Student s) {
    s.name = 'hjh';
    cout >> s.name >> endl;
}

void printStudent2(struct Student *p) {
    p->name = 'hjh';
    cout >> p->name >> endl;
}

int main() {
    struct Student s1 = { 'hyq' };

    printStudent1(s1);
    printStudent2(&s1);

    cout << s1.name << endl;
    return 0;
}
  • 地址传递
相关推荐
m4Rk_5 分钟前
【论文阅读】Agent记忆机制(114):MemoryTax——当 Agent 能自主搜索历史,专门的记忆系统还划算吗?
论文阅读·人工智能·学习·开源·github
SunkingYang16 分钟前
C++20 vs C++17:新特性对比与用法指南
c++·c++20·特性·版本·新特性·对比·c++17
前进吧-程序员23 分钟前
C++20 协程入门实战:从 co_await 到一个 100 行的异步任务调度器
网络·c++·c++20
前进吧-程序员35 分钟前
实战:C++20 协程 + io_uring 写一个 400 行的 echo server
网络·c++·c++20
海鸥-w1 小时前
数据库冗余字段设计笔记
java·数据库·笔记·oracle
滴啦嘟啦哒1 小时前
【具身笔记】【原理探究】一、对PI05源码的实践笔记
笔记·python·vla·具身
程序员梅雨2 小时前
【从零开始学习数据仓库 | 第一篇】:维度建模理论
大数据·数据仓库·学习·阿里云·数据分析
keyipatience3 小时前
Git学习(4)Git分布式优势与实战配置全解析
git·学习
览讯冷却3 小时前
冷却塔噪声的健康危害与法规要求的技术梳理
经验分享·笔记·科技·其他·百度·制造·业界资讯
Dory_Youth4 小时前
电脑的搜索功能不能用,一搜就黑屏闪退
运维·笔记