### Finding the actual size of an array

Hello guys, I'm new to arrays and as I was reading through I found that the number of elements in an array can actually be less than the size of the array e.g (7/10). So I came across this code below in a textbook on how to process only the actual elements. The problem is that I don't get how this program knows that the variable <listSize> is for the actual array size since it's just an integer with no value...pliz help

void initialize(int list[], int listSize)
{
int count;

for (count = 0; count < listSize; count++)
list[count] = 0;
}
I believe the easier thing to do here would be this:
`sizeof(list);`
This returns a special unsigned integer of type size_t. This code is actually a function that takes two values- the pointer of the array, and its size. Of course, it only really needs one, but alas. Also, this function doesn't process anything. It sets the array to zero.
Note that `sizeof()` is a unary compile time operator, which returns the number of bytes in the expression.

You can use `sizeof()` to find the number of elements in an array like so:

 ``123`` ``````typedef int _Ty; _Ty list[10]//assuming int is 4bytes, list should be 40bytes. unsigned short numElements = sizeof(list)/sizeof(_Ty);//40bytes / 4bytes = 10 elements ``````

But if you find yourself calculating the size of an array like this, I guarantee you that you could have done things better to begin with.
Last edited on
Hence why it would be easier to just use `size()`.
The only reason you would even need to do sizeof is if it is a dynamic array but it doesn't seem like his code is using dynamic arrays so he could probably just use the constant variable used to create the array for the size.
It's just a matter of using whatever makes the most sense in a particular situation. Example:
 ``12345`` `````` int array [] = { 1, 3, 5, 7, 11, 4, 2 }; const int size = sizeof(array)/sizeof(array[0]); cout << "size = " << size << endl;``````

Here, I wanted to be able to freely modify the contents of the array by changing the list of values on the first line. Getting the compiler to derive the value for size is less dangerous than manually counting the number of initialisers - human beings make mistakes, so get the computer to do it :)
Topic archived. No new replies allowed.