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?
When we pass a variable to function we are just passing the value of function. But when we pass an array we are passing somehow a pointer because when we do some changes on an array inside a function, actual array gets changed.
In C function, arguments are always passed by value. In case, when an array (variable) is passed as a function argument, it passes the base address of the array. The base address is the location of the first element of the array in the memory.
To pass an array as a parameter to a function, pass it as a pointer (since it is a pointer). For example, the following procedure sets the first n cells of array A to 0. void zero(int* A, int n) { for(int k = 0; k < n; k++) { A[k] = 0; } } Now to use that procedure: int B[100]; zero(B, 100);
Just like normal variables, simple arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.
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"); // Not a single f*ck given.
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 std::string
, std::string&
or std::string const&
(depending on whether you need to modify the object, and whether you want to copy).
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