Hi guys. I'm studying pointers right now and had already figured out how to pass pointer by reference into the function void (T *&name), then I've tried to pass pointer to array by reference into the function, but I've failed. I browsed a lot but didn't find a hint, only how to pass array by reference void (T (&name)[size]). So my qustion is: how to pass pointer to array by reference into the function and if it's possible?
There are only two reasons for passing something by reference.
1. Speed (but passing by value can be just as fast with some compiler optimizations)
2. To modify the variable locally, but also keep those modifications for wherever the function was called.
I can justify wanting to modify the array contents (which the pointer already allows you to do), but why would you want to modify the pointer to an array?
I wrote an example for passing a pointer to an array by reference anyways. http://cpp.sh/8lwg3
This shows that regular arrays are passed by reference. (This is because regular arrays are actually just constant pointers to memory that is guaranteed to be allocated.)
Thanks! So as I understand there is the only way to pass pointer to array by value void (T (*name)[size]), but no way to pass that pointer to array by reference, only the way with usual pointer (your first sample).
So as I understand there is the only way to pass pointer to array by value
Pointers are passed by value such as xs in void f(int xs[5])
or such as xs in void f(int* xs)
It makes no sense to pass a pointer to a statically allocated array by reference, and in my example you can see that it also does not make much sense to pass a pointer to a dynamic array by reference either.
Looking at your samples, I see that the best ways to work with arrays or dynamic arrays is through the pointers. Like this: T* ptr = new T[size]; T arr[size] = { ... }; T* ptr = &arr[0];
So if we can to work with pointers like in samples above, what is the purpose of such pointer T arr[size] = { ... }; T (*ptr)[size] = &arr; . In a book I found explanation of such syntax but without any practical purpose, what the difference between it and samples above? Thanks.
There is no purpose for aliasing arr to ptr. In fact, aliasing is generally a bad thing to do as it has the possibility of introducing bugs and ruining optimization of the compiler