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

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

相关推荐
风流 少年1 小时前
Julia
开发语言·julia
江畔柳前堤1 小时前
GO01-Go 语言与主流编程语言深度对比
开发语言·人工智能·后端·微服务·云原生·golang·go
:-)2 小时前
算法-归并排序
java·开发语言·数据结构·算法·排序算法
GIS阵地3 小时前
QgsRasterDataProvider 完整详解(QGIS 3.40.13 C++)
开发语言·c++·qt·开源软件·qgis
yaoxin5211234 小时前
462. Java 反射 - 获取声明类与封闭类
java·开发语言·python
阿里嘎多学长4 小时前
2026-07-14 GitHub 热点项目精选
开发语言·程序员·github·代码托管
charlie1145141915 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
2501_914245935 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
Hazenix6 小时前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦6 小时前
GO_复合类型---指针
开发语言·后端·golang