The notion of "length" is a sort of tricky one in C (and low-level programming in general). If you have an array, the C compiler knows how large it is and provides an interface to the programmer to get that value in bytes: sizeof
. The thing is, arrays are passed via pointers in C and determining the size via pointers is impossible without certain meta-information. Common methods to determine the length of an array are
appending an end marker to the array. Determining the length is simply a matter of iterating until the end marker is found and returning the number of iterations. Note that this renders the end marker's value unavailable for use as a value in the array.
just passing the size of the array around. Take the write
system call as an example. Besides the file handle, it needs a pointer to the data and its length. Why its length as well? Because the pointer doesn't contain information about the length. So, either use a terminator like a null byte or pass the length explicitly. The former idea can be abandoned because the write
system call is supposed to be generic; and to yield genericity, a null byte must be expected to be a possible value in the array, so it cannot be used as a terminator for reasons I uttered above.
Which one you actually end up using totally depends on the particular use case.
Apparently you decided to use the terminator-variant. \0
is the null byte, an ASCII character with code value 0x0
. It's commonly used for terminating C-strings. strlen
uses it to determine a C-string's length, for example.
For int
arrays, there is no such predefined terminator, so you need to come up with your own one. If you decide on \0
, so be it, but I'd use the literal 0x0
instead because strictly-speaking, \0
is a character literal and that's just unfitting for int
s.
To actually implement this, you'd need to append the terminating value to every int
array, whose size you want to determine this way. Then write your function to get the length of such an int
array just as you do, i.e., by iterating until the terminator is found.