I am new to c++, from my understanding I have been thinking that if I pass address of a vector in a function call like fun(vector<int>&v)
then the values don't get copied into a new vector of int, and any changes made will reflect back, and if in case of fun(vector<int> v)
values get copied.
But when reading this link from geeksfrogeeks I realised that even if '&' is not there the changes on the vector made inside the function will retain after it ends.
here is the code:
/* This function prints all nodes that are distance k from a leaf node
path[] --> Store ancestors of a node
visited[] --> Stores true if a node is printed as output. A node may be k
distance away from many leaves, we want to print it once */
void kDistantFromLeafUtil(Node* node, int path[], bool visited[],
int pathLen, int k)
{
// Base case
if (node==NULL) return;
/* append this Node to the path array */
path[pathLen] = node->key;
visited[pathLen] = false;
pathLen++;
/* it's a leaf, so print the ancestor at distance k only
if the ancestor is not already printed */
if (node->left == NULL && node->right == NULL &&
pathLen-k-1 >= 0 && visited[pathLen-k-1] == false)
{
cout << path[pathLen-k-1] << " ";
visited[pathLen-k-1] = true;
return;
}
/* If not leaf node, recur for left and right subtrees */
kDistantFromLeafUtil(node->left, path, visited, pathLen, k);
kDistantFromLeafUtil(node->right, path, visited, pathLen, k);
}
The changes in the visited array made by one function are visible to the second call to KDistanceFromLeafUtil, without using '&', Is this similar to what happens in Java i.e referenced is copied ? Where did I go wrong in understanding it?
As " bool visited[]" is a pointer, it is indeed changed by your function.
If it were a bool or an int for instance, the copy or the argument would have been changed in the function but not the argument itself, and thus you would have seen no effect outside of your function.