Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
mr5 Avatar asked Apr 22 '13 10:04

mr5


People also ask

What is function What are difference between passing an array to a function and passing a single value data item to a function explain using example?

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.

When we pass an array as a function argument the base address of the array will be passed?

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.

What is passing array as parameters?

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

Can we pass array as a parameter of function?

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.


1 Answers

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

like image 74
Konrad Rudolph Avatar answered Oct 07 '22 15:10

Konrad Rudolph