Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ arrays as function arguments

  • Can I pass arrays to functions just as I would do with primitives such as int and bool?
  • Can I pass them by value?
  • How does the function know of the size of the array it is passed?
like image 713
Dr. Acula Avatar asked May 19 '10 17:05

Dr. Acula


People also ask

Can you pass arrays as function arguments in C?

In C programming, you can pass an entire array to functions.

Can an array be a function argument?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). The below example demonstrates the same.

Can one dimensional array be passed as function arguments in C language?

An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C.

How do you call a function with an array as an argument?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.


2 Answers

Can I pass arrays to functions just as I would do with primitives such as int and bool?

Yes, but only using pointers (that is: by reference).

Can I pass them by value?

No. You can create classes that support that, but plain arrays don't.

How does the function know of the size of the array it is passed?

It doesn't. That's a reason to use things like vector<T> instead of T *.

Clarification

A function can take a reference or pointer to an array of a specific size:

void func(char (*p)[13])
{
    for (int n = 0; n < 13; ++n)
        printf("%c", (*p)[n]);
}

int main()
{
    char a[13] = "hello, world";
    func(&a);

    char b[5] = "oops";
    // next line won't compile
    // func(&b);

    return 0;
}

I'm pretty sure this is not what the OP was looking for, however.

like image 64
egrunin Avatar answered Oct 27 '22 03:10

egrunin


You can pass arrays the usual way C does it(arrays decay to pointers), or you can pass them by reference but they can't be passed by value. For the second method, they carry their size with them:

template <std::size_t size>
void fun( int (&arr)[size] )
{
   for(std::size_t i = 0; i < size; ++i) /* do something with arr[i] */ ;
}

Most of the time, using std::vector or another sequence in the standard library is just more elegant unless you need native arrays specifically.

like image 45
Khaled Alshaya Avatar answered Oct 27 '22 05:10

Khaled Alshaya