解释C ++中的Pointer Pass?

dan*_*oll 0 c++ pointers

我有一个C ++函数,其中有两个int,目的是充当计数器,它们在我的主代码中声明为该函数之外。我的目标是使用函数执行的结果来更新计数器变量。

我有这样声明

int cor_letters = 0;
int cor_place = 0;
Run Code Online (Sandbox Code Playgroud)

然后像这样调用我的函数

res = compare(input, secret_word, &cor_letters, &cor_place);
Run Code Online (Sandbox Code Playgroud)

我的compare函数头是:

bool compare(string user_input, string secret, int * correct_letters, int * correct_place)
Run Code Online (Sandbox Code Playgroud)

在我的compare代码中,当我获得计数器的最终值时,我将其更新为:

correct_letters = &cor_l;
correct_place = &cor_p;
Run Code Online (Sandbox Code Playgroud)

在仔细阅读了我的编译器错误之后,我得出了这个解决方案,这似乎可行。但是,我不太明白为什么会这样。首先,我将两个变量的地址传递给函数。但是该函数需要两个指针。因此,指针指向传入变量的地址。

到目前为止,我似乎已经掌握了发生的情况。但是它令我感到困惑的最终分配-指针(注意它们是函数头中的var名称)随后被更新为我正在使用的临时内部函数变量的地址。为什么这会给我带来价值?

我更是一个视觉学习者,仅通过阅读一些文本就很难掌握指针,因此,如果您不介意制作一些快速的文本图来表示正在发生的事情,那将很棒。谢谢

pro*_*-fh 7

我想你最终以

correct_letters = &cor_l;
correct_place = &cor_p;
Run Code Online (Sandbox Code Playgroud)

为了使编译器停止抱怨。
您关于获取局部变量地址的分析是正确的。

您可能想这样做

*correct_letters = cor_l;
*correct_place = cor_p;
Run Code Online (Sandbox Code Playgroud)

为了给函数的变量分配正确的值。

有关引用&)和取消引用*)操作的简要说明

TYPE var_a=..., var_b=...; // some variables of a chosen type
TYPE *ptr=NULL;    // a pointer on such a type, but not referencing anything yet

ptr=&var_a; // now ptr memorises the address of var_a (reference operation)

var_b=*ptr; // access the value which is stored at the address memorised
            // by ptr (dereference operation) in order to read it
            // (here, this has the same effect as   var_b=var_a;   )

*ptr=var_a+var_b; // access the value which is stored at the address memorised
                  // by ptr (dereference operation) in order to alter it
                  // (here, this has the same effect as   var_a=var_a+var_b;   )
Run Code Online (Sandbox Code Playgroud)

  • 可能还有助于添加一个简短的解释,即“ *”充当“取消引用运算符”以访问地址(而不是地址本身)上的对象。也可以通过指向数组的指针来帮助解释`[...]`也用作取消引用。(您的回答很好,这些只是改进的想法,而不是批评) (2认同)