VOOZH about

URL: https://www.geeksforgeeks.org/cpp/using-sizof-operator-with-array-paratmeters-in-c/

⇱ Do Not Use sizeof For Array Parameters in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Do Not Use sizeof For Array Parameters in C

Last Updated : 23 Jul, 2025

Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers. Consider the below program.  


Explanation: This code generates an error as the function fun() receives an array parameter 'arr[]' and tries to find out the 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 2 (size of int* is 8 bytes because its an pointer and pointer occupies the 8 bytes of memory and int is 4) and the for loop inside fun() is executed only two times irrespective of the size of the array. Therefore, sizeof should not be used to get a number of elements in such cases. 

Solution: 

1) Using a separate parameter: A separate parameter of datatype size_t for array size or length should be passed to the fun().  size_t is an unsigned integer type of at least 16 bits. So, the corrected program will be:


Output
The size of the array is: 4
The elements are:
 0 1 2 3 

2) Using Macros: We can even define Macros using #define to find the size of arrays, as shown below,


Output
The size of the array is: 5
The elements are:
 0 1 2 3 4 

3) Using Pointer arithmetic: We can use (&arr)[1] - arr to find the size of the array. Here, arr points to the first element of the array and has the type as int*. And, &arr has the type as int*[n] and points to the entire array. Hence their difference is equivalent to the size of the array.


Output
The size of the array is: 5
The elements are:
 0 1 2 3 4 
Comment
Article Tags: