+ 6
(SOLVED) What is the difference between "T*" arg/"T arg[]" and "T (&arg)[n]",...
...for an array of type T and size n, if there is any, and if there is, which one should I use and when?
8 ответов
+ 2
With "T *arg" you create a pointer of type T and when you initiallize it with an array (dynamically), it can be moved with, for example, "arg++" or made to point at something else. You can't make it point to something constant like when "T" is "char" and you write arg="somearr", because "somearr" is implicitly of type "const char*".
"T arg[]" is a constant (immovable) pointer to an array of random size.
"T (&arg)[n]" isn't really a thing. It would mean an array of n references. We use pointers for this. "T arg[n]" is sufficient if you know the number of things of type T you want to store.
+ 5
Ani Jona 🕊 Exactly. I got this question answered in another place. Basically when passing an array to "T* arg" or "T arg[]" it reduces to a pointer. And with "T (&arg)[n]" function actually sees arg as an array of T (my explanation is probably the worst thing ever, mostly because I'm a beginner)
+ 5
Ani Jona 🕊 Exactly. You have to specify it in arguments.
+ 4
Ani Jona 🕊 but, for example
void fun(int* arg);
arg is a pointer to an integer, no information lost.
Oh, and also "n" has to be constant or just a value, so you can either ask for a fixed size array, or use it like this:
template <size_t Size>
void fun(int (&arg)[Size]);
...
const size_t size = 5;
int arr[size]{ 1, 2, 3, 4, 5 };
fun<size>(arr);
But it's probably a bad example, once again
+ 2
Ani Jona 🕊 I think it's still bad practice (never seen it being taught or used) and you'll be better off using a pointer anyway, because it doesn't take too much memory compared to copying the whole array in order to pass it to something.
+ 2
Alexander Velinov, i was not discussing what is better or recommended :). I merely commented on your answer that it be an array of n references. I thought you might want to fix that, in case I am not mistaken :).
And passing as ref does not copy the array. If Gᑌᗰᗷᗩᒪᒪ is correct about the difference, then the ref will retajn information about the type, while a degeneration to a pointer will lose us that information. So, it might not be too bad. Or are there other reasons that you know of?
+ 2
Gᑌᗰᗷᗩᒪᒪ, if arg is actually an array, then you lose length information.
+ 1
Is not in T (&arg)[n] arg a reference to an array of n T?