C++ 传递指针给函数
C++ 允许传递指针给函数,只需要简单地声明函数参数为指针类型即可
void tm_now(unsigned long *ptr_sec) { // 获取当前的秒数 *ptr_sec = time( NULL ); return; }
我们写一个范例演示下如何使用这个 tm_now()
函数
/** * file: main.cpp * author: 简单教程(www.twle.cn) * * Copyright © 2015-2065 www.twle.cn. All rights reserved. */ #include <iostream> #include <ctime> void tm_now(unsigned long *ptr_sec) { // 获取当前的秒数 *ptr_sec = time( NULL ); std::cout << "timestamp of now is: " << *ptr_sec; std::cout << std::endl; return; } int main () { unsigned long sec; tm_now( &sec ); // 输出实际值 std::cout << "timestamp in sec is :" << sec << std::endl; return 0; }
编译和运行以上范例,输出结果如下
timestamp of now is: 1523415802 timestamp in sec is :1523415802
指针形参 vs 数组形参
能接受指针作为参数的函数,也能接受数组作为参数
/** * file: main.cpp * author: 简单教程(www.twle.cn) * * Copyright © 2015-2065 www.twle.cn. All rights reserved. */ #include <iostream> double avg(double *arr, int size) { double sum = 0; for ( int i = 0; i < size; i++ ) { sum += arr[i]; } return (double)sum/size; } int main () { // 带有 5 个元素的浮点型数组 double some_num[5] = {1024.0, 512.0, 3, 218, 1171}; double avg_num; // 传递一个指向数组的指针作为参数 avg_num = avg( some_num,5 ) ; // 输出返回值 std::cout << "avg of some_num is:" << avg_num << std::endl; return 0; }
编译和运行以上范例,输出结果如下
avg of some_num is:585.6