C++

C++指针参数问题

纪录

Posted by Gavin on December 14, 2019

共眠一舸听秋雨

小簟轻裘各自寒

问题描述

刷题时,向通过将指针传递给函数,改变其指向的位置,将结果返回,却发现指针依然指向原来的位置,因此打算探究一下

编程探究

#include <iostream>
#include <vector>
#include <map>
using namespace std;

void FindNumsAppearOnce(vector<int> &data,int *num1,int *num2) {
	cout << "The pointers themselves' addresses in function: " << endl;
	cout << &num1 << " " << &num2 << endl;
    map<int, int*> m;
    for (int i = 0; i < data.size(); ++i) {
        if (m.count(data[i]) > 0) m[data[i]] = nullptr;
        else m[data[i]] = &data[i];
    }
    auto iter = m.begin();
    while (iter != m.end() && iter->second == nullptr) iter++;
    num1 = iter->second;
    iter++;
    while (iter != m.end() && iter->second == nullptr) iter++;
    num2 = iter->second;
    cout << "Addresses given to pointers in function: " << endl;
    cout << num1 << " " << num2 << endl;

}

int main(int argc, char const *argv[])
{
	vector<int> data = {2,4,3,6,3,2,5,5};
	cout << "The target address: " << endl;
	cout << &data[1] << " " << &data[3] << endl;
	int *num1, *num2;
	cout << "Addresses which pointers are pointing to before using function: " << endl;
	cout << num1 << " " << num2 << endl;
	cout << "The pointers themselves' addresses: " << endl;
	cout << &num1 << " " << &num2 << endl;
	FindNumsAppearOnce(data,num1,num2);
	cout << "Addresses which pointers are pointing to after using function: " << endl;
	cout << num1 << " " << num2 << endl;
	//cout << *num1 << " " << *num2 << endl;
	return 0;
}

结果分析

发现函数体内指针参数本身的地址并非我想要传给函数的两个指针的地址,因此函数是将指针参数当作普通参数处理的,函数体内给其创建了临时变量,将指针地址当作值传给临时变量,因此要解决问题,我应该传递指向指针的指针,要将指针本身的地址安全传递给函数才行