*& 有什么用?函数参数中的平均值

2021-12-29 00:00:00 function parameters c++

如果我有一个接受 int *& 的函数,这意味着什么?如何仅将 int 或 int 指针传递给该函数?

If I have a function that takes int *&, what does it means? How can I pass just an int or a pointer int to that function?

function(int *& mynumber);

每当我尝试传递指向该函数的指针时,它都会说:

Whenever I try to pass a pointer to that function it says:

error: no matching function for call to 'function(int *)'
note: candidate is 'function(int *&)'

推荐答案

它是对 int 指针的引用.这意味着有问题的函数可以修改指针以及 int 本身.

It's a reference to a pointer to an int. This means the function in question can modify the pointer as well as the int itself.

你可以只传递一个指针,一个复杂的问题是指针需要是一个左值,而不仅仅是一个右值,例如

You can just pass a pointer in, the one complication being that the pointer needs to be an l-value, not just an r-value, so for example

int myint;
function(&myint);

单独是不够的,也不允许 0/NULL,如:

alone isn't sufficient and neither would 0/NULL be allowable, Where as:

int myint;
int *myintptr = &myint;
function(myintptr);

可以接受.当函数返回时,myintptr 很可能不再指向它最初指向的内容.

would be acceptable. When the function returns it's quite possible that myintptr would no longer point to what it was initially pointing to.

int *myintptr = NULL;
function(myintptr);

如果函数希望在给定 NULL 指针时分配内存,也可能有意义.检查随函数提供的文档(或阅读源代码!)以了解如何使用指针.

might also make sense if the function was expecting to allocate the memory when given a NULL pointer. Check the documentation provided with the function (or read the source!) to see how the pointer is expected to be used.

相关文章