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?
The size of int[] is basically counting the number of elements inside that array. To get this we can use the sizeof() operator. If the array name is passed inside the sizeof(), then it will return total size of memory blocks that are occupied by the array.
To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.
The size of a signed int or unsigned int item is the standard size of an integer on a particular machine. For example, in 16-bit operating systems, the int type is usually 16 bits, or 2 bytes. In 32-bit operating systems, the int type is usually 32 bits, or 4 bytes.
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 ;-)] }
The "standard" C way to do this is
sizeof(list) / sizeof(list[0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With