Q. Can the sizeof operator be used to tell the size of an array passed to a function?
No. There's no way to tell, at runtime, how many elements are in an array parameter just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element. This is a Good Thing. It means that passing pointers and arrays to C functions is very efficient.
It also means that the programmer must use some mechanism to tell how big such an array is. There are two common ways to do that. The first method is to pass a count along with the array. This is what memcpy() does, for example:
char source[ MAX ], dest[ MAX ];
/* ... */
memcpy( dest, source, MAX );
The second method is to have some convention about when the array ends. For example, a C "string" is just a pointer to the first character; the string is terminated by an ASCII NUL ('\0') character. This is also commonly done when you have an array of pointers; the last is the null pointer. Consider the following function, which takes an array of char*s. The last char* in the array is NULL; that's how the function knows when to stop.
voidprintMany(
char*strings[] )
{
int
i;
i =
0;
while
( strings[ i ] != NULL )
{
puts( strings[ i ] );
++i;
}
}
Most C programmers would write this code a little more cryptically:
voidprintMany(
char*strings[] )
{
while
( *strings )
{
puts( *strings++ );
}
}
C programmers often use pointers rather than indices. You can't change the value of an array tag, but because strings is an array parameter, it's really the same as a pointer. That's why you can increment strings. Also,
while ( *strings )
means the same thing as
while ( *strings != NULL )
and the increment can be moved up into the call to puts().
If you document a function (if you write comments at the beginning, or if you write a "manual page" or a design document), it's important to describe how the function "knows" the size of the arrays passed to it. This description can be something simple, such as "null terminated," or "elephants has numElephants elements." (Or "arr should have 13 elements," if your code is written that way. Using hard coded numbers such as 13 or 64 or 1024 is not a great way to write C code, though.)
No comments:
Post a Comment