Skip to content
Related Articles

Related Articles

Do not use sizeof for array parameters
  • Difficulty Level : Medium
  • Last Updated : 04 Dec, 2019

Consider the below program.




#include<stdio.h>
void fun(int arr[])  
{
  int i;   
  
  /* sizeof should not be used here to get number 
    of elements in array*/
  int arr_size = sizeof(arr)/sizeof(arr[0]); /* incorrect use of sizeof*/
  for (i = 0; i < arr_size; i++) 
  {  
    arr[i] = i;  /*executed only once */
  }
}
  
int main()
{
  int i;  
  int arr[4] = {0, 0 ,0, 0};
  fun(arr);
    
  /* use of sizeof is fine here*/
  for(i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
    printf(" %d " ,arr[i]);
  
  getchar();  
  return 0;
}    


Output: 0 0 0 0 on a IA-32 machine.

The function fun() receives an array parameter arr[] and tries to find out number of elements in arr[] using sizeof operator.
In C, array parameters are treated as pointers (See this for details). So the expression sizeof(arr)/sizeof(arr[0]) becomes sizeof(int *)/sizeof(int) which results in 1 for IA 32 bit machine (size of int and int * is 4) and the for loop inside fun() is executed only once irrespective of the size of the array.

Therefore, sizeof should not be used to get number of elements in such cases. A separate parameter for array size (or length) should be passed to fun(). So the corrected program is:




#include<stdio.h>
void fun(int arr[], size_t arr_size)  
{
  int i;   
  for (i = 0; i < arr_size; i++) 
  {  
    arr[i] = i;  
  }
}
  
int main()
{
  int i;  
  int arr[4] = {0, 0 ,0, 0};
  fun(arr, 4);
    
  for(i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
    printf(" %d ", arr[i]);
  
  getchar();  
  return 0;
}    


Please write comments if you find anything incorrect in the above article or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :