carraysfunction-parameter

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


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?


Solution

  • 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)