†(This answer is for c++17 users...)
where no need of using sizeof
operator at all.
Use instead std::size()
function which will get you the size of the given container or array.
#include <iostream>
#include <iterator> // std::size
#include <cstddef> // std::size_t
int main()
{
int a[]{ 22,53,13,65,80,31,46 };
for (std::size_t i = 0; i < std::size(a); i++)
{
std::cout << a[i] << `\n`;
}
}
† Update
The OP has edited the question after posting this answer,
where the std::size
can not be applied.
When the array a
passed to void array_output(int a[])
, it deduced to void array_output(int* a)
instead if of the its actual type int a[7]
.
i<(sizeof(a)
output shows first 4
elements
Here, you are doing size of(int*)
(pointer to int), depending up
on the architecture
it could be efferent. In your case it is 32
bit machine which is why you got sizeof(a) = 4
.
i < sizeof(a)/ sizeof(a[0])
output shows only the first element
Dividing sizeof(a)
(which is sizeof(int*
) equal to 4
bytes in
your machine) by sizeof(a[0])
(which is sizeof(int)
, also 4
bytes), is nothing but one and loops only once.
The @Timo's
answer, provide a templated function where size will be a non-type template parameter, which can be accessed directly, without going for sizeof
.
How can I put sizeof
in function and run an output showing all the
elements of an array?
This is possible only when passing the array a
of actual type as it is.
For that, let the array to deduce to its int [7]
, by forwarding it perfectly.
#include<iostream>
template<typename Type>
void array_output(Type&& a) // deduced to `int a[7]`
{
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++) { // or std::size(a)
std::cout << a[i] << '\n';
}
}
int main()
{
int a[] = { 22, 53, 13, 65, 80, 31, 46 };
array_output(a);
return 0;
}