sizeof

asc
Last edited on
first line: sizeof(files)/sizeof(files[0]) means 'size of array/size of one element' and that is the number of elements in the array.
second line: if you don't know what strstr does, see http://www.cplusplus.com/reference/clibrary/cstring/strstr/
Last edited on
sizeof(files) / sizeof(files[0]) is being used to calculate the number of elements in an array.

given an array declared like this:

int files[] = {1,2,3,4,5};
The compiler will calculate the array size from the given number of initializer values.
In this case the compiler know the array has 5 elements.

So sizeof(files) will return 5 *sizeof(int) - which assuming sizeof an integer is 4 bytes will give us a value 0f 20 bytes for the sizeof the entire array.

sizeof(files[0]) will give us the size in bytes of the first element in the array (for this example we are assuming size of integer is 4 bytes).

So sizeof(files) / sizeof(files[0]) will give 20/4 = 5 elements in the array.

Note:
This calculation can only be used in the scope of the function in which the array is declared because when you pass an array to another function you are not really passing an array, you will be passing a pointer
(in this case you will be passing an int * )and the calculation would make no sense in the function that is called.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void wrong_array_size_calculation_function( int files [])
{
  cout << sizeof(files) / sizeof(files[0]) << endl; //wrong
}

int main()
{
  
  int files[] = {1,2,3,4,5};
  cout << sizeof(files) / sizeof(files[0]) << endl; //ok
  wrong_array_size_calculation_function( files);
  return 0;

}

acaca
Last edited on
assxsax
Last edited on
Yes they are the same.
sizeof(files) / sizeof(files[0]);
sizeof is actually the number of bits, so the total number of bits divided by the bits in first element gives you the size of the array because all array elements are the same number of bits, 4 I think. Let me know if I'm wrong about that.
Last edited on
axassxsx
Last edited on
foobarbaz wrote:
Let me know if I'm wrong about that.


You are wrong - sizeof returns the size in bytes
thanks. bytes not bits, got it. Is it 4 bytes each element
Last edited on
another way of getting the length of an array.
template<class T, size_t size> size_t len(T(&)[size]){ return size; }

though this note should still be considered
guestgulkan wrote:
Note:
This calculation can only be used in the scope of the function in which the array is declared because when you pass an array to another function you are not really passing an array, you will be passing a pointer
Topic archived. No new replies allowed.