How sizeof recognize the end of array

1
2
3
string  array[] = { "23", "5", "-10", "0", "0", "321", "1", "2", "99", "30" };
int elements = sizeof(array) / sizeof(array[0]);
std::sort(array, array + elements);


In this program how the sizeof command determine the size of array?
Is there a special character at the end of array?
Last edited on
The sizeof operator returns the size in bytes of a variable or type.
http://en.cppreference.com/w/cpp/language/sizeof
(I couldn't find the definition for sizeof on this site due to all the questions about it...)

sizeof(array) is the size of the whole array

sizeof(array[0]) is the size of the first element in the array

So sizeof(array)/sizeof(array[0]) is the same as <size of the whole array>/<size of one element>, which is (obviously?) the number of elements.

You could also have used, in your case (as each element is a string)

int elements = sizeof(array) / sizeof(string);

but the form you gave is the standard one, as it works whatever type the array holds.

Andy

P.S. If you use VC++, you should use the _countof() macros instead.

const int elements = _countof(array); // if it doesn't need to change, make it const

It is defined in <stdlib.h> / <cstdio>. It does the same calculation as above, but checks that the variable is actually an array.
Last edited on
sizeof is not a normal function. It is a built in command that will resolve the size of it's argument at compile time. There is no way to tell where an array ends unless you make one (such as marking the end with a special value).
Topic archived. No new replies allowed.