c++结构体传参

复制代码
//
// Created by 徐昌真 on 2024/10/5.
//
#include <iostream>
using namespace std;

//定义一个结构体
struct Circle{
    int x, y, r;
};

//定义一个可以修改结构体内容的函数
void movePoint(Circle c, int x, int y){
    c.x += x;
    c.y += y;
}

//定义一个可以输出结构体内容的函数
void printCircle(Circle c){
    cout << '(' << c.x << ',' << c.y << ") " << c.r << endl;
}

int main() {

    //创建一个结构体
    Circle c = {1,2,3};
    //调用修改结构体的函数
    movePoint(c,1,2);
    //调用输出结构体的函数
    printCircle(c);

    return 0;
}

我们这样子写完之后 会发现修改的结果并没有生效 这是因为值的改变只在函数的内部 并没有在main函数内部改变 我们需要用指针 在地址里面修改值 才可以

这是输出结果

这是修改后的代码

复制代码
//
// Created by 徐昌真 on 2024/10/5.
//
#include <iostream>
using namespace std;

//定义一个结构体
struct Circle{
    int x, y, r;
};

//定义一个可以修改结构体内容的函数
void movePoint(Circle* c, int x, int y){
    c->x += x;
    c->y += y;
}

//定义一个可以输出结构体内容的函数
void printCircle(Circle c){
    cout << '(' << c.x << ',' << c.y << ") " << c.r << endl;
}

int main() {

    //创建一个结构体
    Circle d = {1,2,3};
    //调用修改结构体的函数
    movePoint(&d,1,2);
    //调用输出结构体的函数
    printCircle(d);

    return 0;
}

我们只需传入指针类型的数据即可

相关推荐
Yu_Lijing几秒前
基于C++的《Head First设计模式》笔记——状态模式
c++·笔记·设计模式
23124_802 分钟前
热身签到-ctfshow
开发语言·python
鱼跃鹰飞3 分钟前
Leetcode1027:最长等差数列
java·数据结构·算法
翱翔的苍鹰10 分钟前
CIFAR-10 是一个经典的小型彩色图像分类数据集,广泛用于深度学习入门、模型验证和算法研究
深度学习·算法·分类
小白学大数据13 分钟前
移动端Temu App数据抓包与商品爬取方案
开发语言·爬虫·python
顶点多余14 分钟前
静态链接 vs 动态链接,静态库 vs 动态库
linux·c++·算法
吃吃喝喝小朋友16 分钟前
JavaScript文件的操作方法
开发语言·javascript·ecmascript
AI视觉网奇19 分钟前
ue5 开发 web socket server 实战2026
c++·学习·ue5
2301_7973122619 分钟前
学习Java42天
java·开发语言·学习
2501_9445264220 分钟前
Flutter for OpenHarmony 万能游戏库App实战 - 知识问答游戏实现
android·开发语言·javascript·python·flutter·游戏·harmonyos