C++概念帮助指针

C++概念帮助指针,c++,pointers,C++,Pointers,因此,我对指针有一个合理的理解,但有人问我它们之间的区别是什么: void print(int* &pointer) void print(int* pointer) 我自己还是个学生,我不是100%。我很抱歉,如果这是基本的,但我的谷歌技能失败了我。你能帮我更好地理解这个概念吗。我已经很久没有用C++了,我正在尝试辅导一个学生,我正在努力巩固我的概念知识。 < P>第一个指针通过引用,第二个通过值。 如果使用第一个签名,则可以修改指针指向的内存以及它指向的内存 例如: void p

因此,我对指针有一个合理的理解,但有人问我它们之间的区别是什么:

void print(int* &pointer)

void print(int* pointer)

我自己还是个学生,我不是100%。我很抱歉,如果这是基本的,但我的谷歌技能失败了我。你能帮我更好地理解这个概念吗。我已经很久没有用C++了,我正在尝试辅导一个学生,我正在努力巩固我的概念知识。

< P>第一个指针通过引用,第二个通过值。 如果使用第一个签名,则可以修改指针指向的内存以及它指向的内存

例如:

void printR(int*& pointer)   //by reference
{
   *pointer = 5;
   pointer = NULL;
}
void printV(int* pointer)    //by value
{
   *pointer = 3;
   pointer = NULL;
}

int* x = new int(4);
int* y = x;

printV(x);
//the pointer is passed by value
//the pointer itself cannot be changed
//the value it points to is changed from 4 to 3
assert ( *x == 3 );
assert ( x != NULL );

printR(x);
//here, we pass it by reference
//the pointer is changed - now is NULL
//also the original value is changed, from 3 to 5
assert ( x == NULL );    // x is now NULL
assert ( *y = 5 ;)

第一个通过引用传递指针,第二个通过值传递指针

如果使用第一个签名,则可以修改指针指向的内存以及它指向的内存

例如:

void printR(int*& pointer)   //by reference
{
   *pointer = 5;
   pointer = NULL;
}
void printV(int* pointer)    //by value
{
   *pointer = 3;
   pointer = NULL;
}

int* x = new int(4);
int* y = x;

printV(x);
//the pointer is passed by value
//the pointer itself cannot be changed
//the value it points to is changed from 4 to 3
assert ( *x == 3 );
assert ( x != NULL );

printR(x);
//here, we pass it by reference
//the pointer is changed - now is NULL
//also the original value is changed, from 3 to 5
assert ( x == NULL );    // x is now NULL
assert ( *y = 5 ;)

第一个通过引用传递指针。 如果通过引用传递,函数可以更改传递参数的值

void print(int* &pointer)
{
  print(*i);  // prints the value at i
  move_next(i);  // changes the value of i. i points to another int now
}

void f()
{
  int* i = init_pointer();
  while(i)
    print(i);  // prints the value of *i, and moves i to the next int.
}

第一个通过引用传递指针。 如果通过引用传递,函数可以更改传递参数的值

void print(int* &pointer)
{
  print(*i);  // prints the value at i
  move_next(i);  // changes the value of i. i points to another int now
}

void f()
{
  int* i = init_pointer();
  while(i)
    print(i);  // prints the value of *i, and moves i to the next int.
}