1

How do i get the size of array in void Func(int (*a)[5]) for loop condition and print elements?

void Func(int (*a)[5])
{
   for (int i = 0; i < 5; i++)
      cout << a[i]; // doesn't work
}

int main()
{
   int a[] = {1, 2, 3, 4, 5};
   Func(&a);
}
user743211
  • 13
  • 2

7 Answers7

3

Using a function template would be better if you major emphasis is on passing the size of the array.

template <typename T, size_t N>
void Func(T (&a)[N])
{  
    for (int i = 0; i < N; i++)
      cout << a[i]; 
}
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
3

Firstly, the way you access the array is wrong. Inside your function you have a pointer to an array. The pointer has to be dereferenced first, before you use the [] operator on it

void Func(int (*a)[5])
{
   for (int i = 0; i < 5; i++)
      cout << (*a)[i];
}

Secondly, i don't understand why you need to "get" the size of the array, when the size is fixed at compile time, i.e. it is always 5. But in any case you can use the well-known sizeof trick

void Func(int (*a)[5])
{
   for (int i = 0; i < sizeof *a / sizeof **a; i++)
      cout << (*a)[i];
}

The sizeof *a / sizeof **a expression is guaranteed to evaluate to 5 in this case.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

It doesn't work because you didn't de-reference it enough. You have a pointer to an array- the pointer requires de-referencing, and the array needs indexing.

void Func(int (*a)[5])
{
   for (int i = 0; i < 5; i++)
      std::cout << (*a)[i];
}

int main()
{
   int a[] = {1, 2, 3, 4, 5};
   Func(&a);
}
Puppy
  • 144,682
  • 38
  • 256
  • 465
0

When you pass an array into a function, it degrades to a pointer and all size information is lost.

jonsca
  • 10,218
  • 26
  • 54
  • 62
0

You can instead use a STL container, like vector, to make things easier.

#include <iostream>
#include <vector>
using namespace std;

void Func(vector <int> a){
   for (int i = 0; i < a.size(); i++)
   cout << a[i];
}

int main (){
       int nums[] = {1, 2, 3, 4, 5};
       vector<int> a (nums, nums + sizeof(nums) / sizeof(int) );
       Func(a);
}
Jesufer Vn
  • 13,200
  • 6
  • 20
  • 26
0

How do i get the size of array

You already know the size at compile-time, it's 5. You just forgot to dereference the pointer:

cout << (*a)[i];
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • What about `int size = sizeof(*a)/sizeof(int);`? – user743211 May 12 '11 at 18:50
  • @user: You already told the compiler that you point to an array of 5 integers. What else do you hope to find out about the array? Yes, `sizeof(*a)/sizeof(int)` will yield 5, but again, you already know that. – fredoverflow May 12 '11 at 18:57
-1
void Func(int * a)
{
   for (int i = 0; i < 5; i++)
      cout << *(a+i);
}

int main()
{
   int a[] = {1, 2, 3, 4, 5};
   Func(a);
}
J T
  • 4,946
  • 5
  • 28
  • 38