Why as a programmer we don’t use the sizeof the operator for array parameters?

Share Your Love

The sizeof() is a function but it’s called an operator, which returns the size of a particular variable in memory. It both uses in C and C++ programming languages. So, here is a question why as a programmer we don’t use the sizeof the operator for array parameters?

Suppose 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

The above output depends on IA-32 Machine.

The function fun() receives array(arr[]) as parameter and tries to find out number of elements in an arr[] using sizeof operator.

Generally in C array parameters are treated as pointer.

So, the expression sizeof(arr)/sizeof(arr[0]) means sizeof(int *)/sizeof(int) which results in 1 for IA-32 bit machine both size of int and int * is 4 and the for loop inside fun() is executed only once irrespective of the sizeof array.

Therefore the sizeof operator should not be used to get number of elements in such cases. A separate parameter for an array size or length and should be passed to fun().

So the right 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;
}	

If you feel this information helpful then please share and comments on it. And if you want to improve the article then please WhatsApp me.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter