+ 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?

12th May 2022, 7:51 PM
🇺🇦 GUMBALL 🇺🇦 [Dead account]
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.
14th May 2022, 7:05 PM
Alexander Velinov
Alexander Velinov - avatar
+ 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)
14th May 2022, 7:58 PM
🇺🇦 GUMBALL 🇺🇦 [Dead account]
+ 5
Ani Jona 🕊 Exactly. You have to specify it in arguments.
15th May 2022, 8:02 AM
🇺🇦 GUMBALL 🇺🇦 [Dead account]
+ 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
14th May 2022, 8:21 PM
🇺🇦 GUMBALL 🇺🇦 [Dead account]
+ 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.
14th May 2022, 8:05 PM
Alexander Velinov
Alexander Velinov - avatar
+ 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?
14th May 2022, 8:08 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
Gᑌᗰᗷᗩᒪᒪ, if arg is actually an array, then you lose length information.
15th May 2022, 4:54 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Is not in T (&arg)[n] arg a reference to an array of n T?
14th May 2022, 7:51 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar