tags:

views:

358

answers:

7

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??

+8  A: 

The "standard" C way to do this is

sizeof(list) / sizeof(list[0])
Carl Smotricz
is there any other way?
adam
Apparently yes, since you're asking about C++. Lots of other answers.
Carl Smotricz
+14  A: 

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;
}
Prasoon Saurav
+1 for mentioning std::vector. No, adam, there is no other way, and this won't work on arrays whose size isn't known to the compiler (such as parameters passed in as int[]).
BlueRaja - Danny Pflughoeft
oh i see. So there is no way i can get the right size when passing array to a function? Thanks
adam
How to pass array by reference please??
adam
But you have to know the size of that array in advance if you pass the array by reference to any function to correctly print the size of that array inside that function.
Prasoon Saurav
You don't have to know the size of the array, you can make it a template. See my answer.
avakar
+4  A: 

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
Mehrdad Afshari
Better to parenthesize the entire expression so that expressions like `index % COUNTOF(x)` work like you'd expect.
Adam Rosenfield
Adam: Thanks for pointing out. Pretty important issue.
Mehrdad Afshari
+2  A: 

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().

Dirk Eddelbuettel
+4  A: 

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.

avakar
That one really surprised me when I first ran across it.
Richard Pennington
Isn't C++ the most awesome language ever? :)
avakar
This looks neat! How does this work? And how do you call it?
Default
@Michael : Read [this](http://stackoverflow.com/questions/2384107/magic-arguments-in-function-templates) thread and [my answer here](http://stackoverflow.com/questions/2037736/finding-size-of-int-array/2037742#2037742) which shows how to call this function.
Prasoon Saurav
...wait for the next c++ standard or have a look at this thread: http://stackoverflow.com/questions/1500363/compile-time-sizeof-array-without-using-a-macro
Viktor Sehr
@Prasoon: How wierd, I must have skipped by your answer and not seen that you also gave this solution.. thanks for the links :)
Default
+1  A: 

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

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

This, however, does not give you a compile-time constant, so you can't do something like:

int a[20];

char x[countof(a)];

If you really want to support that, 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).

Jerry Coffin
A: 

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.

coming out of void