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;
}

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

相关推荐
dog25012 小时前
阿基米德的有限步逼近思想求圆面积
算法
CircleMouse12 小时前
springboot项目中使用Java 8的日期时间API
java·开发语言·spring boot·后端·spring
想做功的洛伦兹力112 小时前
2026/2/13日打卡
算法
仟濹13 小时前
【算法打卡day7(2026-02-12 周四)算法:BFS and BFS】 3_卡码网107_寻找存在的路线_并查集
数据结构·算法·图论·宽度优先
YuTaoShao13 小时前
【LeetCode 每日一题】3713. 最长的平衡子串 I ——(解法二)暴力枚举 + 优化
算法·leetcode·职场和发展
蜡笔小马13 小时前
20.Boost.Geometry 中常用空间算法详解:crosses、densify、difference 与离散距离度量
c++·算法·boost
Mr YiRan13 小时前
C++语言学习之面向对象
java·c++·学习
rgb2gray13 小时前
优多元分层地理探测器模型(OMGD)研究
人工智能·算法·机器学习·回归·gwr
前端达人13 小时前
被JavaScript忽视的Web Animations API:为什么说它是前端动画的真正未来?
开发语言·前端·javascript·ecmascript