Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the size of an int[]? [duplicate]

Tags:

c++

arrays

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?

like image 950
adam Avatar asked Jan 10 '10 17:01

adam


People also ask

How do you find the int size?

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.

How do you find the size of an 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.

What is size of int how it is defined?

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.


2 Answers

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 ;-)] } 
like image 126
Prasoon Saurav Avatar answered Oct 05 '22 15:10

Prasoon Saurav


The "standard" C way to do this is

sizeof(list) / sizeof(list[0]) 
like image 31
Carl Smotricz Avatar answered Oct 05 '22 16:10

Carl Smotricz