开发者

Passing an array by pointer

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

开发者_JAVA百科
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);
}


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.


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]; 
}


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);
}


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


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);
}


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];


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜