C++: Passing a struct containing an array as arg, do I need to pass as pointer?

arrays, c++, struct

Solution

Will the array be copied correctly when I pass a struct S to that function

Yes, it will be copied.

do I have to change the function to: `void some_fun( struct S * myS )`

You may want to do that for three reasons:

- You want to avoid copying - passing a pointer is cheaper

- You want to make changes to the struct inside `some_fun` - pointers let you do that; passing by value does not

- You want to reduce the risk of stack overflow - if the array is large, passing by value may overflow the stack. Passing by pointer greatly reduces this risk.

EDIT : Since this is C++, you have an option of passing the `struct` by reference:

void some_fun( S& myS ) // struct keyword is optional in C++

or

void some_fun( const S& myS ) // Do this if you do not plan on modifying myS

Passing by reference avoids copying in a way similar to passing by pointer. Unlike passing by pointer, passing by reference indicates to the reader that the `struct` passed in references some place in memory, while pointers give you an option of passing a `NULL`.

Problem

If I have a struct like so: ``` struct S { int arr[10]; int x; } ``` If I have a function ``` void some_fun( struct S myS ); ``` Will the array be copied correctly when I pass a struct S to that function or do I have to change the function to: ``` void some_fun( struct S * myS ); ? ``` I have tested this (and it works without a pointer) but I am a bit unsecure about C/C++, sometimes it works even though it is wrong.

Original source

Related problems