gpt4 book ai didi

c++ - 修改指针在 C++ 函数中指向的位置

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:56:14 24 4
gpt4 key购买 nike

我一直坚持修改指针的指针。问题是我不明白为什么我的代码有效。我想要做的是修改指针到指针指向函数中的位置。然后在我的主要功能中访问该值。我尝试了很多次,这是我让它工作的唯一方法。

#include <iostream>
using namespace std;
void changePP(int **ppint) {
int *n = new int;
*n = 9; //just a value for demonstration purposes
*ppint = n; //THE LINE IN QUESTION
delete n;
}
int main() {
int **ppint = NULL;
int *p = new int;
*p = 4; //another value for demonstrating
ppint = &p;
cout << **ppint << endl;
changePP(ppint);
cout << **ppint << endl;
}

因此,输出是 4,然后在不同的行上输出 9。但是,我不确定代码中的 *ppint = n 行。为什么我必须使用 * 来更改 ppint 在 changePP 函数中而不是在 main 中指向的位置?另外为什么我不必在函数中使用 & ?我似乎无法在互联网上找到我可以理解的解释,我想知道是否有人可以为我解释一下?

最佳答案

注意:这些内存地址只是为了说明。

内存布局

0x0A | 4
0x0B | 'p' -> 0x0A // Pointer to the value 4 in location 0x0A
0x0C | 'ppint' -> NULL // Initially a null pointer

执行 ppint = &p; 会产生以下结果,因为这里的 ppint 是位于 0x0C 的指针。

0x0A | 4
0x0B | 'p' -> 0x0A
0x0C | 'ppint' -> 0x0B

至于changePP 函数中的参数,为了避免混淆,我将其称为ppintCopy。它是一个拷贝(即不同于 ppint 的指针)并且修改它只会修改拷贝。

0x0D | 'ppintCopy' -> 0x0C // A pointer that points to `ppint`

执行 ppintCopy = &n 会修改 0x0D 处的指针,这不是 main 函数中指针的位置。 但是,引用ppintCopy(即*ppintCopy)会产生0X0C,它是main 的指针 函数因此 *ppintCopy = n; 正在改变指针 0x0C 指向的位置。

Why do I have to use the * to change where ppint points to in the changePP function but not in the main?

通过上面的说明,我希望它能更清楚为什么它在 main 中工作以及为什么您必须在 changePP 函数中使用不同的语法。

Also why do I not have to use the & in the function?

main 函数中,变量 ppintint** 类型(即指向指针的指针)和 pint* 类型。您不能执行 ppint = p; 因为它们是不同的类型。如果您删除一层间接寻址,这可能更容易看到。例如:

int* pMyInt = NULL;
int myInt = 3;

我认为这是不言自明的,这是行不通的(即,它们是不同的类型)。

pMyInt = myInt;

然而,您可以使用 & 运算符获取 myInt 的地址,这会导致指向 int 的指针(即 int*)和由于此类型与 pMyInt 的类型相同,因此现在可以进行赋值。

pMyInt = &myInt;

关于c++ - 修改指针在 C++ 函数中指向的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28910673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com