我想知道我们何时在C++中使用Pointer指针以及为什么我们需要指向指针?我知道当我们指向一个指针时,这意味着我们将变量的内存地址保存到内存中,但我不知道为什么需要它?另外我看到一些例子总是在创建矩阵时使用指针到指针!但为什么Matrix可能需要Pointer指针?
当您想更改作为函数参数传递给函数的变量的值,并在该函数之外保留更新的值时,您需要指向该变量的指针(单指针)。
void modify(int* p)
{
*p = 10;
}
int main()
{
int a = 5;
modify(&a);
cout << a << endl;
}
Run Code Online (Sandbox Code Playgroud)
现在,当您想要更改作为函数参数传递给函数的指针的值时,您需要指向指针的指针。
简而言之,**当您想要保留(或保留更改)内存分配或分配甚至在函数调用之外时使用。(因此,使用双指针 arg 传递此类函数。)
这可能不是一个很好的例子,但会向您展示基本用法:
void safe_free(int** p)
{
free(*p);
*p = 0;
}
int main()
{
int* p = (int*)malloc(sizeof(int));
cout << "p:" << p << endl;
*p = 42;
safe_free(p);
cout << "p:" << p << endl;
}
Run Code Online (Sandbox Code Playgroud)
当我们想要更改它所指向的指针的地址时,我们基本上需要指针到指针。一个很好的例子是链表的情况,当我们尝试向开头插入一个值时,我们发送一个指向头节点的指针。下面粘贴了代码片段。
int main()
{
/* Start with the empty list */
struct node* head = NULL;
/* Use push() to construct below list
1->2->1->3->1 */
push(&head, 1);
push(&head, 2);
.....
....
}
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));
.....
.....
}
Run Code Online (Sandbox Code Playgroud)
这基本上是因为,假设一个指针最初指向一个内存位置0X100,我们想要更改它以将其指向其他位置(比如)0X108。在这种情况下,传递的是指向指针的指针。
何时在C++中使用指针指针?
我想说永远不要在C++中使用它会更好.理想情况下,你只需要使用C API或一些传统的东西,还涉及到或设计时考虑到Ç的API打交道时使用它.
C++语言功能和附带的标准库几乎已经过时了指针指针.你有什么时候想要传递一个指针并在一个函数中编辑原始指针的引用,对于像指向一个字符串数组的指针这样的东西你最好使用一个std::vector<std::string>.这同样适用于多维数组,矩阵等等,C++有更好的方法来处理这些事情,而不是指针的神秘指针.