finding size of int array

0 votes
asked Jan 10, 2010 by adam

How to find size of an int array? eg:

int list[]={1,5,7,8,1,1,4,5,7,7,7,8,10,20};

how to the size of list?

I know for char array. We can use strlen(array) to find the size, or check with '\0' at the end of the array.

But for int array, checking '\0' seems not working.

Problem!!!!!!!!!! sizeof(array)/sizeof(array[0]) only works in main??? If i use it inside a function. eg:

  #include <iostream>

  using namespace std;
  void size(int arr1[]){
    int size;
    size=sizeof(arr1)/sizeof(arr1[0]);
    cout<<size<<endl;
  }

  int main(){
  int list_1[]={1,5,7,8,1,1,4,5,7,7,7,8,10,20};
  size(list_1);

  return 0;
}

It can not print the right size??

9 Answers

0 votes
answered Jan 10, 2010 by carl-smotricz

The "standard" C way to do this is

sizeof(list) / sizeof(list[0])
0 votes
answered Jan 10, 2010 by prasoon-saurav

Try this:

sizeof(list)/sizeof(list[0]);

Because this question is tagged C++, it is always recommended to use std::vector in C++ rather than using conventional C-style arrays.


EDIT : (because the question has been edited)

An array-type is implicitly converted into a pointer-type when you pass it to a function. Have a look at this.

In order to correctly print the sizeof an array inside any function, pass the array by reference to that function(but you need to know the size of that array in advance)

EDIT 2 : Adam wants to know how to pass the array by reference

#include <iostream>


template<typename T,int N> 
//template argument deduction
void size(T (&arr1)[N]) //Passing the array by reference 
{
   size_t size;
   size=sizeof(arr1)/sizeof(arr1[0]);  

   std::cout<<size<<std::endl; //Correctly prints the size of arr

   //EDIT

   std::cout<<N; //Correctly prints the size too [cool trick ;-)]
}

int main()
{
   int list_1[]={1,5,7,8,1,1,4,5,7,7,7,8,10,20};
   size(list_1);

   return 0;
}
0 votes
answered Jan 10, 2010 by mehrdad-afshari

You can't do that for a dynamically allocated array (or a pointer). For static arrays, you can use sizeof(array) to get the whole array size in bytes and divide it by the size of each element:

#define COUNTOF(x) (sizeof(x)/sizeof(*x))

To get the size of a dynamic array, you have to keep track of it manually and pass it around with it, or terminate it with a sentinel value (like '\0' in null terminated strings).

Update: I realized that your question is tagged C++ and not C. You should definitely consider using std::vector instead of arrays in C++ if you want to pass things around:

std::vector<int> v;
v.push_back(1);
v.push_back(2);
std::cout << v.size() << std::endl; // prints 2
0 votes
answered Jan 10, 2010 by dirk-eddelbuettel

Besides Carl's answer, the "standard" C++ way is not to use a C int array, but rather something like a C++ STL std::vector<int> list which you can query for list.size().

0 votes
answered Jan 10, 2010 by avakar

You could use boost::size, which is basically defined this way:

template <typename T, std::size_t N>
std::size_t size(T const (&)[N])
{
    return N;
}

Note that if you want to use the size as a constant expression, you'll either have to use the sizeof a / sizeof a[0] idiom or wait for the next version of the C++ standard.

0 votes
answered Jan 10, 2010 by jerry-coffin

Since you've marked this as C++, it's worth mentioning that there is a somewhat better way than the C-style macro:

template <class T, size_t N>
size_t countof(const T &array[N]) { return N; }

This has the advantage that if you accidentally try to pass something other than an array to it, the code simply won't compile (whereas passing a pointer to the C macro will compile but produce a bad result. The disadvantage is that this doesn't give you a compile-time constant, so you can't do something like this:

int a[20];

char x[countof(a)];

In C++11 or newer, you can add constexpr to get a compile-time constant:

template <class T, size_t N>
constexpr size_t countof(const T &array[N]) { return N; }

If you really want to support the same on older compilers, there is a way, originally invented by Ivan Johnson, AFAIK:

#define COUNTOF(x)  (                                           \
  0 * sizeof( reinterpret_cast<const ::Bad_arg_to_COUNTOF*>(x) ) +  \
  0 * sizeof( ::Bad_arg_to_COUNTOF::check_type((x), &(x))      ) +  \
  sizeof(x) / sizeof((x)[0])  )                                  


class Bad_arg_to_COUNTOF
{
public:
   class Is_pointer;
   class Is_array {};  
   template<typename T>
   static Is_pointer check_type(const T*, const T* const*);
   static Is_array check_type(const void*, const void*);
};

This uses sizeof(x)/sizeof(x[0]) to compute the size, just like the C macro does, so it gives a compile-time constant. The difference is that it first uses some template magic to cause a compile error if what you've passed isn't the name of an array. It does that by overloading check_type to return an incomplete type for a pointer, but a complete type for an array. Then (the really tricky part) it doesn't actually call that function at all -- it just takes the size of the type the function would return, which is zero for the overload that returns the complete type, but not allowed (forcing a compile error) for the incomplete type.

IMO, that's a pretty cool example of template meta programming -- though in all honesty, the result is kind of pointless. You really only need that size as a compile time constant if you're using arrays, which you should normally avoid in any case. Using std::vector, it's fine to supply the size at run-time (and resize the vector when/if needed).

0 votes
answered Jan 10, 2010 by coming-out-of-void

when u pass any array to some function. u are just passing it's starting address, so for it to work u have to pass it size also for it to work properly. it's the same reason why we pass argc with argv[] in command line arguement.

0 votes
answered Sep 15, 2017 by rashedcs

You have to use sizeof() function.

Code Snippet:

#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);

      int arr[] ={5, 3, 6, 7};

      int size = sizeof(arr) / sizeof(arr[0]);
      cout<<size<<endl;

      return 0;
}
0 votes
answered Sep 15, 2017 by yuchao-jiang

The best way is to use distance method which is based on the iterator. For example:

int a[] ={1,2,3,4};
cout<< distance(begin(a),end(a));
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...