2

I'm trying to find the length of an array with the code below, but when I'm trying to run it inside of a function, it doesn't work right.

int nums1 []={1,2,3,4,5,6,7,8,9,10};
const int len1=sizeof(nums1)/sizeof(nums1[0]);

When I'm passing nums1 to the function and then trying to find the length of nums1, same code doesn't work right.

This is my codes and what I get as a result:

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
AnilCan
  • 33
  • 6

2 Answers2

2

The size of a pointer is something different than the size of an array, the pointer might point to. When you pass or assign an array to a pointer, it decays into a pointer to the first element. And the C++ programming language (just like C) has no implicit mechanism to convey the size across such decay.

You'll have to specify the number of elements explicitly as an additional parameter to the function. Or just use a std::vector instead.

datenwolf
  • 159,371
  • 13
  • 185
  • 298
2

To rewrite the two examples

const int len1 = sizeof(int[10]) / sizeof(int)

and

const int len2 = sizeof(int*) / sizeof(int);

The first one takes the size of an int array, whereas the second one takes the size of an int pointer. In your architecture, an int is 4 bytes long, and an array of 10 ints is therefore 40 bytes long. A pointer on the other side, takes 8 bytes on this architecture (most likely 64 bit).

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198