【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;
}
  • 地址传递
相关推荐
BlackWolfSky几秒前
鸿蒙中级课程笔记2—状态管理V2—@Provider装饰器和@Consumer装饰器:跨组件层级双向同步
笔记·华为·harmonyos
橘子师兄9 分钟前
C++AI大模型接入SDK—deepseek接入封装
c++·人工智能·chatgpt
胖少年17 分钟前
Ubuntu 24.04 LTS apt autoremove 误删依赖致程序崩溃 解决与预防笔记
linux·笔记·ubuntu
Shea的笔记本19 分钟前
MindSpore实战笔记:Pix2Pix图像转换复现全记录
笔记·算法·机器学习·web3
Yeats_Liao22 分钟前
长文本优化:KV Cache机制与显存占用平衡策略
人工智能·深度学习·学习·机器学习·华为
清酒难咽22 分钟前
算法案例之蛮力法
c++·经验分享·算法
解局易否结局23 分钟前
学习Flutter for OpenHarmony的前置 Dart 语言:基础语法实战笔记(上)
笔记·学习·flutter
散峰而望34 分钟前
【数据结构】假如数据排排坐:顺序表的秩序世界
java·c语言·开发语言·数据结构·c++·算法·github
天使之一1 小时前
目前工作单位换成了设计院了
学习
zzcufo1 小时前
s7-1500plc与modbustcp通讯错误报16#80c8
学习