Home c++ example of the need to use a link to a pointer

example of the need to use a link to a pointer

Author

Date

Category

hello, I wanted to find an example of the mandatory use of a link to a pointer … I could not find it …
here, let’s say there is a code:

template & lt; typename T & gt;
void ptr_diff (T * & amp; ptr, size_t length) {
  delete [] ptr;
  ptr = new T [length];
  for (unsigned i = 0u; i & lt; length; ++ i) {
    ptr [i] = i;
  }
}
int main () {
int * ptr = new int [5];
  for (unsigned i = 0u; i & lt; 5; ++ i) {
    ptr [i] = i * i;
  }
  for (unsigned i = 0u; i & lt; 5; ++ i) {
    std :: cout & lt; & lt; ptr [i] & lt; & lt; "";
  }
  std :: cout & lt; & lt; std :: endl;
  ptr_diff (ptr, 5);
  for (unsigned i = 0u; i & lt; 5; ++ i) {
    std :: cout & lt; & lt; ptr [i] & lt; & lt; "";
  }
}

unfortunately, everything worked out correctly, the values ​​by the pointer changed … even if there was ptr_diff (T * & amp; ptr, size_t length), even without a reference to the pointer …
Please write some implementation of the ptr_diff function such that you definitely need the signature of the ptr_diff (T * & amp; ptr, size_t length) function with a reference to the pointer, otherwise so that the value by the pointer does not change or something else happens to it


Answer 1, authority 100%

Everything worked right for you precisely because you are passing a pointer to the function by reference

template & lt; typename T & gt;
void ptr_diff (T * & amp; ptr, size_t length) {
       ^^^^
// ...

If you remove the link from the function declaration

template & lt; typename T & gt;
void ptr_diff (T * ptr, size_t length) {
       ^^^^
// ...

you will see that everything will work, or rather not work, in a different way. 🙂

Since you delete the memory in the function that was originally allocated in main for the pointer ptr , and this pointer does not receive a new value, since the function deals with a copy of the pointer rather than the pointer itself.

Therefore, after calling the function, this loop has undefined behavior

ptr_diff (ptr, 5);
for (unsigned i = 0u; i & lt; 5; ++ i) {
  std :: cout & lt; & lt; ptr [i] & lt; & lt; "";
}

and will most likely crash because there is an attempt to access memory that has already been freed by a function call.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions