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

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

相关推荐
Bona Sun14 小时前
单片机手搓掌上游戏机(十二)—esp8266运行gameboy模拟器之编译上传
c语言·c++·单片机·游戏机
帅中的小灰灰14 小时前
C++编程观察者设计模式
数据库·c++·设计模式
z***y86214 小时前
Java数据挖掘开发
java·开发语言·数据挖掘
软件开发技术深度爱好者14 小时前
Python库/包/模块管理工具
开发语言·python
小白程序员成长日记14 小时前
2025.11.21 力扣每日一题
算法·leetcode·职场和发展
bubiyoushang88814 小时前
基于MATLAB的自然图像梯度分布重尾特性验证方案
开发语言·matlab
MSTcheng.15 小时前
【C++STL】priority_queue 模拟实现与仿函数实战
开发语言·c++
还有几根头发呀15 小时前
从 C++ 的角度,系统地解释 进程(Process)、线程(Thread)、协程(Coroutine) 的概念、原理、优缺点,以及常见应用场景。
c++
oioihoii15 小时前
Python与C++:从哲学到细节的全面对比
c++
小年糕是糕手15 小时前
【C++】C++入门 -- inline、nullptr
linux·开发语言·jvm·数据结构·c++·算法·排序算法