how can "auto&" deduce "int []"

1
2
3
4
5
6
7
8
  #include<iostream>
using namespace std;

int main() {
	int b[] = { 1,2,3 };
	auto& a = b;  // int &a[3] = b;
	cout << typeid(a).name() << endl; // int [3]
}

how can "auto" deduce the exactly type of "b" when "int &a[3] =b "is wrong?
how to initialize array variable "a" by another array variable "b"?
> when "int &a[3] =b "is wrong?

int &a[3] is wrong "because references are not objects, there are no arrays of references, no pointers to references, and no references to references".
https://en.cppreference.com/w/cpp/language/reference

> how to initialize array variable "a" by another array variable "b"

Use std::array https://en.cppreference.com/w/cpp/container/array

This is fine:
1
2
3
4
5
6
7
int b[] { 1, 2, 3 } ; // array of three int
int (&a)[3] = b ; // fine: lvalue reference to array of three int
// int c[3] = b ; // *** error: arrays can't be copy initialised

std::array<int,3> d { { 1, 2, 3 } } ;
std::array<int,3> e = d ; // fine: std::array can be copy initialised
d = e ; // fine: std::array can be copy assigned 


if you want to declare a reference to an array.You ought to declare like this:
int(&a)[3] = b;

"()" is necessary.
if you want to initialize array variable "a" by another array.
You can:
int c[3] = { 4,5,6 };
for (std::size_t i = 0; i != 3; ++i)
a[i] = c[i];

Here is my code, I hope it can help you.
int b[3] = { 1,2,3 };
int(&a)[3] = b;
int c[3] = { 4,5,6 };
for (std::size_t i = 0; i != 3; ++i)
a[i] = c[i];
for (const auto& elem : b)
std::cout << elem << " ";

The output is 4,5,6 Because you change the elements in "b" through reference "a".
Last edited on
For info an auto - and in particular with ref to auto& - see:

https://en.cppreference.com/w/cpp/language/auto

Note that there is also decltype() and that this may not result in the same type as using auto. See:

https://en.cppreference.com/w/cpp/language/decltype

Topic archived. No new replies allowed.