passing parameters in functions having struct

I have hard time understand below. Could anyone please advise? Thank you.

1
2
3
4
5
6
7
8
9
10
struct vehicle truck;//first we have this declaration

void foo(struct vehicle &);//second we have this function
foo(&truck) //can we pass this argument to above function?
************************************************************

struct vehicle truck;//first we have this declaration

void foo(struct vehicle *);//second we have this function
foo(*truck) //can we pass this argument to above function? 
Last edited on
┬┐why don't just test it and read the error messages?
When & is in a function declaration like your example:
void foo(struct vehicle &);//second we have this function
it means that you are passing a variable without copying it. If you didn't have the &, you would be copying the variable. In your example, this means the vehicle is not being copied. This is important if you want to make changes to the vehicle without copying it, changing it, and returning an unrelated vehicle. You can also use & on a return type to avoid copying it.

In the other context:
foo(&truck) //can we pass this argument to above function?
The & means you are passing the truck's address. The pointer to the truck. Does foo accept a pointer?


When * is in a function declaration:
void foo(struct vehicle *);//second we have this function
It means you are passing a pointer to a variable. This allows an object to be acted on through a pointer, which also means it is not being copied, but you have to be more careful to prevent corrupting memory.

In the argument context:
foo(*truck) //can we pass this argument to above function?
The * means "get the variable at the address." If you use a bad address (something that isn't a pointer, or a pointer that hasn't been initialized or has been deleted), you can also corrupt memory. Is truck an address?

Most up to date compilers will try and prevent you from corrupting memory, but it is not fool proof.
Last edited on
Thank you!
Registered users can post here. Sign in or register to post.