Reference to Array in C++
Last Updated :
29 Jun, 2021
Reference to an array means aliasing an array while retaining its identity. Reference to an array will not be an int* but an int[]. Let us discuss this in detail by discussing the difference between these two. This is quite weird that int[] is the same as int* but still compiler perspective on both is entirely different. The major two differences are as follows:
- int[] for the compiler is an array, so it provides an iterator for this (that's why we have For-Each Loop) but int* is just a pointer to an integer. This could just be a pointer to integer or pointer to the beginning of integer array which totally depends upon our perspective. Hence, no For-Each loop in this case.
- For compiler, a and b are the same data type i.e int* here for compiler they are just int* pointing to address. But for compiler type of as an array is int[2] and type of b as an array is int[3] which are completely different from each other. Again just the compiler's perspective. For better understanding let the two arrays be int a[2], int b[3].
Implementation:
- Passing an array to function in a classical way.
- Later on, trying to call for-each loop on it, a clear difference can be obtained.
Example:
C++
// C++ Program to demonstrate Above Approach
// Importing input output stream to take input
// and to display anything on the console
#include <iostream>
using namespace std;
// Method 1
// To print array elements
void print(int arr[], size_t n)
{
// Iterating over elements on an array
// using the foreach loop
for (int element : arr) {
// Print the elements of the array
cout << element << " ";
}
// New line as all the desired elements are printed
cout << endl;
}
// Method 2
// Main driver method
int main()
{
// Declaring and initializing Integer array with
// custom input entries
int a[]{ 1, 2, 3, 4 };
size_t size = sizeof(a) / sizeof(a[0]);
// Calling the Method1 as created above
// in the main) method to
// print array elements
print(a, size);
}
Output:
test.cpp: In function 'void print(int*, size_t)':
test.cpp:5:21: error: 'begin' was not declared in this scope
for(int element: arr){
Output Explanation:
Here it is clear that int* doesn't have any information about the underlying array but if you pass an array by reference using the template the above code will work. As reference array retains information about underlying array and its type would be int[4], not int*.
Now let us discuss a reference to an array.
Methods:
- Naive method
- Reference to an Array
Method 1: Naive method
First most the common way that comes into our mind is described below syntactically. This is clearly a Naive approach as it loses its array identity.
int a[] = {1, 2, 3, 4};
int *b = a;
Note: int a[] = b; will not work as array can only be initialized using aggregate object
Method 2: Reference to Array
- The size needs to be mentioned as int[x] and int[y] are different data types from the compiler's perspective.
- Reference to array needs to be initialized at the time of declaration.
- (&name) is not redundant. It has its own meaning.
Syntax:
data_type (&name)[size] = array;
Note: data_type &name[size] is incorrect because it means an array of reference to some datatype which is clearly meaningless. By doing so we have “name” of data type int (&) [] which is, of course, different from int[]
Example:
C++
// C++ Program to demonstrate Reference to an Array
// Importing input output classes
#include <iostream>
using namespace std;
// Main driver method
int main()
{
// Creating and initializing an integer array
// Custom input entries
int a[]{ 1, 2, 3, 4 };
// int (&b)[] = a;
// Declaring this way wont work as an error will be
// thrown invalid initialization of reference of type
// ‘int (&)[]’ from expression of type ‘int [4]’ Here
// you see compiler referred to "a" as int [4] not int*
int(&b)[4] = a;
// Iterating over elements using foreach loop
for (int e : b) {
// Print the elements of the array
cout << e << " ";
}
}
Similar Reads
References in C++ In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly.Example:C++#include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x; // printing v
5 min read
Pointer to an Array in C++ Pointers in C++ are variables that store the address of another variable while arrays are the data structure that stores the data in contiguous memory locations. In C++, we can manipulate arrays by using pointers to them. These kinds of pointers that point to the arrays are called array pointers or
6 min read
array::size() in C++ STL The array::size() method is used to find the number of elements in the array container. It is the member method std::array class defined inside <array> header file. In this article, we will learn about the array::size() method in C++.Example:C++// C++ Program to illustrate the use of array::si
2 min read
Array of Vectors in C++ STL Prerequisite: Arrays in C++, Vector in C++ STL An array is a collection of items stored at contiguous memory locations. It is to store multiple items of the same type together. This makes it easier to get access to the elements stored in it by the position of each element. Vectors are known as dynam
3 min read
STD::array in C++ The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
5 min read
array::operator[ ] in C++ STL Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::operator[] This operator is used to reference the element present at position given inside the operator.
2 min read
Array of Strings in C++ In C++, a string is sequence of characters that is used to store textual information. Internally, it is implemented as a dynamic array of characters. Array of strings is the array in which each element is a string.We can easily create an array of string in C++ as shown in the below example:C++#inclu
4 min read
Pointers and References in C++ In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
Pointers vs Array in C++ Arrays and pointers are two derived data types in C++ that have a lot in common. In some cases, we can even use pointers in place of arrays. But even though they are so closely related, they are still different entities. In this article, we will study how the arrays and pointers are different from e
3 min read
How to print size of array parameter in C++? How to compute the size of an array CPP? C++ // A C++ program to show that it is wrong to // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize(int arr[]) { cout << sizeof(arr) << endl; } int main() { int a[10]; cout << si
3 min read