Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the size of integer array

Tags:

arrays

c

How to find the size of an integer array in C.

Any method available without traversing the whole array once, to find out the size of the array.

like image 809
AGeek Avatar asked May 05 '10 12:05

AGeek


People also ask

What is the size of integer 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.

Is there array size () in C++?

array::size() in C++ STL The introduction of array class from C++11 has offered a better alternative for C-style arrays. size() function is used to return the size of the list container or the number of elements in the list container.

How do you find the size of an array in Java?

To get the size of a Java array, you use the length property. To get the size of an ArrayList, you use the size() method.

How do you find the byte size of an array?

If we want to determine the size of array, means how many elements present in the array, we have to write the calculation with the help of sizeof operator. Sizeof( arr [] ) / sizeof (arr[0]) ; Here, the size of arr[] is 5 and each integer takes memory 4 bytes. So, the total memory is consumed = ( 5 * 4 ) bytes.


1 Answers

If the array is a global, static, or automatic variable (int array[10];), then sizeof(array)/sizeof(array[0]) works.

If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);) or passed as a function argument (void f(int array[])), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0]) compiles just fine even for the second case, but it will silently produce the wrong result.

like image 191
sbi Avatar answered Sep 26 '22 01:09

sbi