【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;
}
  • 地址传递
相关推荐
c238563 小时前
MySQL 基础用法(上):库表管理与数据增删改
c语言·数据库·c++·mysql
尤乐娃子3 小时前
进入大厂(厂子大)实习Day12
前端·笔记·实习
光源【时光寸寸又逢君】4 小时前
第三方平台预览我方级联监控点串流问题排查
c++·iot
键盘会跳舞4 小时前
C++:容器适配器 queue 的源码级拆解
开发语言·c++·queue
砚凝霜5 小时前
软考网络工程师|第 6 章 密码学、哈希、数字签名、数字证书 PKI 完整备考笔记
笔记·密码学·哈希算法
YuforiaCode5 小时前
第十六届蓝桥杯 2025 C/C++组 数列差分
c语言·c++·蓝桥杯
QAQo7T5 小时前
Python组蓝桥杯备赛超详细知识点总结笔记_排序算法篇
笔记·python·算法·蓝桥杯·排序算法
千里之行,始于足下sanhai5 小时前
P8686 [蓝桥杯 2019 省 A] 修改数组 - 数字魔法大冒险 题解
c++·算法·动态规划
lion_heart0015 小时前
成功日记Plus 智能记账:共享账本、预算管控、Excel 导出等一次讲清
笔记
小星星闪亮登场5 小时前
Codeforces Round 1115 ( Div. 2)
数据结构·c++·算法·贪心算法·排序算法·codeforces