c++arrayspointers

Difference between passing array, fixed-sized array and base address of array as a function parameter


I am confused about which syntax to use if I want to pass an array of known or unknown size as a function parameter.

Suppose I have these variants for the purpose:

void func1(char* str) {
    //print str
}

void func2(char str[]) {
    //print str
}

void func3(char str[10]) {
    //print str
}

What are the pros and cons of using each one of these?


Solution

  • All these variants are the same. C just lets you use alternative spellings but even the last variant explicitly annotated with an array size decays to a normal pointer.

    That is, even with the last implementation you could call the function with an array of any size:

    void func3(char str[10]) { }
    
    func("test"); // Works.
    func("let's try something longer"); // The compiler doesn’t care.
    

    Needless to say this should not be used: it might give the user a false sense of security (“oh, this function only accepts an array of length 10 so I don’t need to check the length myself”).

    As Henrik said, the correct way in C++ is to use a strongly typed buffer. Depending on your use-case and the actual meaning of the parameter, this could either be a string type (e.g. std::string1 or std::string_view), a byte buffer (std::vector<char>1 or an iterator-delimited range) or a fixed-width range or slice (std::array<char, N>, std::span<char, N>).


    1 usually as a (const) reference