Search code examples
c++arrayssize

Calculating an array's number of elements... Able to refer to its index values by just stating the return type? What? How? Why? (C++)


I am learning how to calculate the size and number of elements in an array and came across a question. In a tutorial I see we can calculate the number of elements in an array as follows ...

int array_variable [] = {1, 5, 8, 10};

int array_variable_number_of_elements = sizeof(array_variable) / sizeof (int);

I am aware and fully understand why you could replace

sizeof (int);

with

sizeof (array_variable[0]); // or use any index value from the array_variable

The video appears to suggest using just int is good practice which I don't understand. The computer obviously isn't psychic and int is simply a data type. What happens when there are two int type arrays in the same function? Why does this work? Does this work because it is in the same line as the following?

int array_variable_number_of_elements = sizeof(array_variable)

Thanks :)


Solution

  • Second approach is better and more generic, when you need to change the type of array int to char, you don't have to edit second line at all.

      char array_variable [] = {'a', 'b', 'c' }; //changed this line only
        
      int array_variable_number_of_elements = sizeof(array_variable) / sizeof 
      (array_variable[0]);
    

    To answer your below comment;

    above lines you can interpret like below;

    
      int array_variable = {1, 2, 3, 4, 5 };
        
      int array_variable_number_of_elements = sizeof(array_variable) / sizeof ( int);
     //              ^^^^^^^^^                  ^^^^                 ^^^
    //  array_variable_number_of_elements =       20     /     4 ; // 20 / 4 = 5
    

    total array size in bytes 20 and size of int is 4 bytes in my system; total number of elements in array is 5;