example of the need to use a pointer reference
Hello, I wanted to find an example of mandatory use of a pointer reference... I never found it... here, let's say, there is a code:
template<typename T>
void ptr_diff(T*& ptr, size_t length) {
delete[] ptr;
ptr = new T[length];
for(unsigned i=0u; i<length; ++i) {
ptr[i] = i;
}
}
int main() {
int* ptr = new int[5];
for(unsigned i=0u; i<5; ++i) {
ptr[i] = i*i;
}
for(unsigned i=0u; i<5; ++i) {
std::cout<<ptr[i]<<" ";
}
std::cout<<std::endl;
ptr_diff(ptr, 5);
for(unsigned i=0u; i<5; ++i) {
std::cout<<ptr[i]<<" ";
}
}
Unfortunately, everything worked correctly, the values on the pointer changed... even if there were ptr_diff(T*& 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 function (T*& ptr, size_t length) with a reference to the pointer, otherwise, so that the value of the pointer does not change or something else happens to it
1 answers
Everything worked out correctly for you precisely because you pass a pointer to the function by reference
template<typename T>
void ptr_diff(T*& ptr, size_t length) {
^^^^
//...
If you remove the reference from the function declaration
template<typename T>
void ptr_diff(T* ptr, size_t length) {
^^^^
//...
Then you will see that everything will work, or rather not work, in a different way.:)
Since you are in the function deleting the memory that you originally allocated in main
for the pointer ptr
, and this pointer does not get a new value, since the function is dealing with a copy of the pointer, and not with the pointer itself.
Therefore further, after calling the function, this loop has an undefined behavior
ptr_diff(ptr, 5);
for(unsigned i=0u; i<5; ++i) {
std::cout<<ptr[i]<<" ";
}
And most likely it will crash, because there is an attempt to access memory that has already been released by calling the function.