c++ - 双指针有必要吗?

标签 c++ c pointers reference pass-by-reference

void test(int *p2) {
    *p2 = 3;}

int main()
{

int* p1, x = 5;

p1 = &x;
test(p1); // p1 and p2 are pointing to the same address which is x's address
printf("%d", x); //prints 3    

这个例子有2个指针指向同一个地址,它们通过引用传递给函数。

现在看第二个例子

void test(int **p2) {
    **p2 = 3;
}
int main()
{

    int* p1, x = 5;

    p1 = &x;
    test(&p1); // p2 is pointing to p1 address
    printf("%d", x);

那么在这种情况下双指针是必要的吗?尤其是结构化链表?

typedef struct NOde {
    int data;
    struct NOde* next;
}node;
void test(node *head) {
    node* new_node = (node*)malloc(sizeof(node));
    new_node->data = 5;
    new_node->next = head; 
    head= new_node; 
}
int main()
{
    node* head=NULL;

    test(head);

如果与上面的概念相同,为什么在这个中,main 中的 header value 仍然NULL

最佳答案

当您想要更改指针所指向的地址的内容时,指针 (*p) 就足够了。

当您想要更改指针指向的地址时,需要双星指针 (**p)。

在下面的代码中,特别检查第二个 printf 语句的结果。

#include <stdio.h>
#include <stdlib.h>

void swapValues(int *p, int val) {
    *p = val;
}

void swapPointers(int **p, int *val) {
    *p = val;
}

int main() {
    int x, y;
    int *p1 = &x;
    int *p2 = &x;

    x = 3;
    y = 5;
    printf("x = %d y = %d p1 = %d p2 = %d\n", x, y, *p1, *p2);
    printf("p1 = %p p2 = %p\n", p1, p2);

    swapValues(p1, y);
    printf("x = %d y = %d p1 = %d p2 = %d\n", x, y, *p1, *p2);
    printf("p1 = %p p2 = %p\n", p1, p2);

    x = 3;
    y = 5;
    swapPointers(&p2, &y);
    printf("x = %d y = %d p1 = %d p2 = %d\n", x, y, *p1, *p2);
    printf("p1 = %p p2 = %p\n", p1, p2); // observe value of p2 here

    return 0;
}

关于c++ - 双指针有必要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320021/

相关文章:

c++ - 另一个使用相同 InnoDB 数据或日志文件的 mysqld 进程

计算 0 到 1 之间随机数的平均值

c - Hangman 程序帮助(C 编程简介)

c - 是否可以混合使用 C 和 Swift?

c - 静态字符数组的含义?

c++ - 作用域 std::unique_ptr 转换

c - memcpy() 将整数值复制到字符缓冲区

c++ - Firemonkey:在运行时将子控件添加到 TListViewItem

c++ - 基本C++头文件问题

php - 相当于 php shell_exec 的 c++