First question:
Many times we pass a reference of one object to another via function call using pointers.For example:
int num =25;
int *num1Ptr=#
int *num2Ptr=NULL;
void assinNum (int *numPtr){
num2Ptr = numPtr; ////we copy the value (address) of the num1Ptr pointer to num2Ptr
}
My question is : if such a method gets called very frequently can we expect a significant overhead of pointers copy?
Second question :
In the following scenario , does it mean we copy the value in the memory address pointed by passed numPtr to the memory address pointed by num2Ptr? If yes ,then it is the same as passing by value ?
int num =25;
int *num1Ptr=#
int *num2Ptr=NULL;
void assinNum (int *numPtr){
*num2Ptr = *numPtr; ////num2Ptr points to the same value in the memory pointed by numPtr argument.
}
Update for the first question:
What are the consequences for the pointers to large objects (not primitives)?
A pointer is usually just a 32-bit or 64-bit quantity. So copying a pointer just involves copying a 32-bit or 64-bit quantity, which is very cheap on most platforms. However, copying an
intdirectly is also very cheap, so in this case, using pointers probably doesn’t bring you much benefit.It’s also worth pointing out that in many situations, the compiler will optimize this function by inlining it.
In theory, yes. However,
num2Ptr = NULL, so your code is likely to cause a segmentation fault.I’m not sure what you’re referring to, so it’s difficult to know how to answer this!