指针参数在C 中接收地址

pointer argument receiving address in c++?

本文关键字:地址 参数 指针      更新时间:2023-10-16
int y=5;
int *yPtr = nullptr;
yPtr = &y;

我了解指针存储y的地址。并致电 *yptr dereences y。

如果我打电话给void函数:

int main()
{
    int number = 5;
    function( &number );
}
void function( int *nPtr)
{
    *nPtr = *nPtr * *nPtr;
}

如果该函数将指针作为参数,则如何调用该函数的呼叫使用地址?我了解NPTR存储的地址,但是为什么不能将其定义为。

void functions (int &ref)
{
    ref = ref * ref;
}

我的主要问题是:为什么接收地址参数的函数需要指针参数才能接收地址?

通过使用传递参数,您可以强制函数,而不是复制参数本身的值,而是使用您提供的实际变量。因此,有关更清晰的视图,请参见下文:

void function( int number )
{
  cout << number;
}
function( myInt ); // function will copy myInt, into its local variables stack

,但是,通过使用通过传递方法,这样:

void function ( int & number )
{
  cout << number
}
function( myInt ); // function will not copy myInt into its local variables stack, instead, it will use the already existent myInt variable.

编译器如何与通过分点和传递参数一起使用没有区别。相反,您的功能的调用看起来像:

void function_p( int *number )
{
  cout << *number;
}
void function_r( int & number )
{
  cout << number;
}
// and the calls
function_p( &myInt ); // it is required to use address-of operator here
function_r( myInt ); // the effect will be the same, but with less effort in writing that address-of operator

在C 11中,程序员通常开始使用通过传递方法,通常是因为它具有更轻松的写作"模板"。


要完成问题的答案,*&操作员仅参考参数的类型,以便创建复合类型。复合类型是一种按其他类型定义的类型。C 有几种化合物类型,其中两种是参考和指针。

您可以理解,它们仅通过以适当的方式编写变量(在我们的情况下)影响变量的类型:

int* p1; // we will read this: pointer p1 points to an int
int* p2 = &var1; // we read this: pointer p2 points to int variable var1
int var1 = 12;
int& ref1 = var1; // and we read this: ref1 is a reference to var1

您通常可以考虑对同一内存块的引用表示不同。

您确实是指

void functions (int &ref)
{
    ref = ref * ref;
}

这就是您使用refs的方式,避免了指针的所有"*"语法

这是C 的古怪事物中的另一种。通过引用传递与传递指针不同。当您做

之类的事情时
void functions (int &ref)

您可以将实际变量传递到 functions(而不是指向它们),例如

int a = 12;
functions(a);

和功能内部您无需退出。请注意,您正在通过参考,而不是通过 a 参考。

当您传递参考或指向某物指针时,您将使用Star这样

void function( int *nPtr)

因此,您必须使用 *

退出

还请注意,您通过将&放在其前面获取变量(或常数),但是您 nequare 通过放置*来获得参考或指针在它的前面。同时,您还将*放在其前面。