How to find the size of an int[]?


Question

I have

int list[] = {1, 2, 3};

How to I get the size of list?

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


I tried sizeof(array) / sizeof(array[0]) as some answers said, but it only works in main? For example:

int size(int arr1[]){
    return sizeof(arr1) / sizeof(arr1[0]);
}

int main() {
    int list[] = {1, 2, 3};

    int size1 = sizeof(list) / sizeof(list[0]); // ok
    int size2 = size(list_1); // no
    // size1 and size2 are not the same
}

Why?

1
40
6/29/2018 10:21:58 PM

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.


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

You would do it like so for the general case

template<typename T,int N> 
//template argument deduction
int size(T (&arr1)[N]) //Passing the array by reference 
{
   return sizeof(arr1)/sizeof(arr1[0]); //Correctly returns the size of 'list'
   // or
   return N; //Correctly returns the size too [cool trick ;-)]
}
51
3/5/2018 5:15:34 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon