0

Why it is used division of sizeof(arr1[0]) to calculate length of array? It can be calulated simply without dividing it with sizeof(arr1[0]). Kindly explain this if anyone knows the reason

   #include <stdio.h>  

int main()  
{  
    //Initialize array   
    int arr1[] = {1, 2, 3, 4, 5};  

    //Calculate length of array arr1  
    int length = sizeof(arr1)/sizeof(arr1[0]);  

    //Create another array arr2 with the size of arr1.  

    int arr2[length];  

    //Copying all elements of one array into another  
    for (int i = 0; i < length; i++) {   
        arr2[i] = arr1[i];   
    }    

    //Displaying elements of array arr1   
    printf("Elements of original array: \n");  
    for (int i = 0; i < length; i++) {   
        printf("%d ", arr1[i]);  
    }  

    printf("\n");  

    //Displaying elements of array arr2   
    printf("Elements of new array: \n");  
    for (int i = 0; i < length; i++) {   
        printf("%d ", arr2[i]);  
    }  
    return 0;  
}
Mujjad
  • 9
  • 3

4 Answers4

2

sizeof(arr) gives you the size in bytes of all the array. sizeof(arr[0]) gives you the size in byte of one element in the array (which is the first element, and all the elements have the same size).

So sizeof(arr1)/sizeof(arr1[0]) gives you how many elements there are in the array

j23
  • 3,139
  • 1
  • 6
  • 13
1

In the programming language C the operator sizeof generates the size of a variable or datatype, measured in the number of bytes required for the type.

sizeof(arr1)

this means size of the whole array arr1 in bytes.

sizeof(arr1[0])

this means size of the first element in bytes.

So the division of both is the length of the array arr. [in elements]

Mike
  • 4,041
  • 6
  • 20
  • 37
0
sizeof(arr1)

Gives size of entire array which is 5 * sizeof(int) bytes, if you want to know the number of elements in the array you need to divide it by size of element which array is holding.

You can even do

int length = sizeof(arr1)/sizeof(int);

but, what if array type changes?

char arr1[] = {1, 2, 3, 4, 5};

your calculation will go for toss or you endup changing every place where length is being calculated.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
0

sizeof() will return the amount in bytes of the argument you give for it. sizeof(arr1) will return the size in bytes of the array arr1. It is different from the number of elements, usually referred to as the array length. To know the length of an array you have to first know the amount of bytes of it and then divide it by the size (in bytes) of each element (i.e. this is what your code sizeof(arr1)/sizeof(arr1[0]) does).

With that said, your code have an error in the line int arr2[length];. The length of arrays must be evaluated to a constant natural number. As length does not represents a constant integer it can not be used in the declaration of arr2 - it is likely that your compiler throws an error to you.

andresantacruz
  • 1,676
  • 10
  • 17