Giải đáp về tham chiếu của con trỏ

Mấy anh cho em hỏi tại sao hai đoạn code dưới đây lại ra đáp án khác nhau vậy ạ (giữa int* &ptr với int* ptr)

Đoạn code này sẽ in ra NULL:

#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

void setToNull(int* &ptr)
{
	ptr = NULL;
}

int main()
{
	int value = 5;
	int* pValue = &value;

	cout << "pValue point to " << pValue << endl;
	setToNull(pValue);
	if (pValue == NULL)
		cout << "pValue point to NULL" << endl;
	else
		cout << "pValue point to " << pValue << endl;
	return 0;
}

Đoạn code này không in ra NULL:

#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;

void setToNull(int* ptr)
{
	ptr = NULL;
}

int main()
{
	int value = 5;
	int* pValue = &value;

	cout << "pValue point to " << pValue << endl;
	setToNull(pValue);
	if (pValue == NULL)
		cout << "pValue point to NULL" << endl;
	else
		cout << "pValue point to " << pValue << endl;
	return 0;
}

Ở đoạn code thứ hai bạn đang gán NULL cho 1 con trỏ hoàn toàn khác, ko liên quan với pValue (ngoài việc lấy giá trị của pValue).
Trong đoạn code thứ nhất ptr đang được cột vào (bind) tham số thực sự pValue, nên bạn đang gán NULL cho pValue.

4 Likes

setToNull(pValue);
Thật ra đoạn này parameter được truyền vào hàm setToNull chỉ là 1 copy của pValue thôi.
Kiểu như bạn tạo ra một con trỏ khác, xong dùng con trỏ đấy đưa vào hàm vậy.

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?