Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:
void foo (int iz[6]) { iz[42] = 43; }
With:
int is[2] = {1,2,3};
we get a useful error. Perhaps it helps with commenting/documentation?
We need to give the size of the array because the complier needs to allocate space in the memory which is not possible without knowing the size.
You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) . In this case the size specified for the leftmost dimension is ignored anyway.
Declaring Arrays:typeName variableName[size]; This declares an array with the specified size, named variableName, of type typeName. The array is indexed from 0 to size-1. The size (in brackets) must be an integer literal or a constant variable.
In case of an array (variable), while passed as a function argument, it decays to the pointer to the first element of the array. The pointer is then passed-by-value, as usual.
Can anyone enlighten me as to why I should bother to specify the size of a C array argument in a function header? For example:
void foo (const char sz[6]) { sz[42] = 43; }
IMO, you shouldn't. When you try to pass an array to a function, what's really passed is a pointer to the beginning of the array. Since what the function receives will be a pointer, it's better to write it to make that explicit:
void foo(char const *sz)
Then, since it's now clear that the function has been given no clue of the size, add that as a separate parameter:
void foo(char const *sz, size_t size)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With