1 / 3
Oct 2013

Can somebody explain the discrepancy in the code here?
Used sizeof() to calculate length of an array

#include <stdio.h>
#include <stdlib.h>
void x(int arr[])
{
	int len=sizeof(arr)/sizeof(arr[0]);
	printf("Length in function x() = %d\n",len);
}
int main()
{
	int arr[10]={0,1,2,3,4,5,6,7,8,9};
	int len=sizeof(arr)/sizeof(arr[0]);
	printf("Length in main function = %d\n",len);
	x(arr);
	return 0;
}
}
  • created

    Oct '13
  • last reply

    Nov '13
  • 2

    replies

  • 381

    views

  • 3

    users

In main, sizeof has access to the newly declared array's size. The type of arr is int[10] there, so sizeof returns 10 * sizeof(int), as expected.
Arrays and pointers aren't the same. for instance, you can't say arr = arr + 2 inside main, because its type (int[10]) is not assignable.

When you pass arr to x, arr "decays" into a pointer. You can now say arr = arr + 2 if you so please, since arr is now just a pointer. Thus, sizeof(arr) will return the size of an int*. If you want sizeof information to remain, and for arr not to decay when passing it, x must take arr by reference, as so:

void x(const int (&arr)[10])

If you do that, then arr, inside x, will have type int[10], and sizeof(arr) will return 10 * sizeof(int).

24 days later

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 14 6d

Want to read more? Browse other topics in C and C++ or view latest topics.