指针及引用传参的一个实例

最近在看代码时,发现了一个有趣的事,通过指针和引用传参,能够在不使用返回值就能实现数据的获取。

#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;

struct Test
{
    int i;
    char buf[12];
};

void fun1(int &num)
{
    num = 25;
}

void fun2(char &buf)
{
    buf = 'A';
}

void fun3(char *buf)
{

    strncpy(buf,"hello",6);
}

void fun4(Test &test)
{
    test.i = 38;
    strncpy(test.buf,"hello world",12);

}
int main(int argc, char const *argv[])
{
    /* code */
    int num;
    char buf1;
    char buf2[6];
    fun1(num);
    fun2(buf1);
    fun3(buf2);

    cout << num << endl << buf1 << endl << buf2 <<endl;

    Test te;
    fun4(te);
    cout << te.i << endl << te.buf << endl;
    
    return 0;
}

使用这种格式简化了代码。

输出打印结果:

25
A
hello
38
hello world

原文地址:https://www.cnblogs.com/KeepThreeMunites/p/11341428.html