简体   繁体   English

C ++概念帮助,指针

[英]c++ concept help, pointers

So i have a reasonable understanding of pointers but i was asked what the difference between these are: 所以我对指针有一个合理的了解,但有人问我这些指针之间有什么区别:

void print(int* &pointer)

void print(int* pointer)

I'm still a student myself and im not 100%. 我本人还是学生,不是100%。 Im sorry if this is basic but my googleing skills failed me. 很抱歉,如果这是基本操作,但我的Google搜索技能使我失败了。 Is there anyway you can help me understand this concept a bit better. 无论如何,您可以帮助我更好地理解这个概念。 I haven't used c++ in a long time, and i am trying to help to tutor a student, and i am trying to solidify my conceptual knowledge for her. 我已经很长时间没有使用c ++了,我正试图帮助一位学生补习课,并且正努力为她巩固我的概念知识。

The first passes the pointer by reference, the second by value. 第一个按引用传递指针,第二个按值传递指针。

If you use the first signature, you can modify both the memory the pointer points to, as well as which memory it points to. 如果使用第一个签名,则可以修改指针指向的内存以及指针指向的内存。

For example: 例如:

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 ;)

The first passes the pointer by reference. 第一个通过引用传递指针。 If you pass by reference the function can change the value of the passed argument. 如果通过引用传递,该函数可以更改传递的参数的值。

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM