Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I declare a C array parameter's size in a function header?

Tags:

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?

like image 388
user2023370 Avatar asked Mar 03 '11 22:03

user2023370


People also ask

Why is it necessary to declare the size of array?

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.

Do you have to declare array size in C?

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.

Which is the correct way to declare an array size?

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.

What happens when an array is passed to a function?

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.


1 Answers

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) 
like image 61
Jerry Coffin Avatar answered Jan 02 '23 22:01

Jerry Coffin