Home > Article > Backend Development > When Should You Use References and When Should You Use Pointers in C ?
Passing by Reference vs. Pointer in C
Determining when to pass by reference and when to pass by pointer can be a confusing matter in C . Let's explore the advantages and disadvantages of each approach.
Passing by Reference
Advantages:
Disadvantages:
Passing by Pointer
Advantages:
Disadvantages:
Best Practices
A general rule of thumb is to "Use references when you can and pointers when you have to." For example:
Example
Consider the following code snippet:
int main() { map<string, shared_ptr<vector<string>>> adjacencyMap; vector<string>* myFriends = new vector<string>(); myFriends->push_back(string("a")); myFriends->push_back(string("v")); myFriends->push_back(string("g")); adjacencyMap["s"] = shared_ptr<vector<string>>(myFriends); return 0; }
In this example, using a pointer to pass myFriends is appropriate because it allows us to create a new vector and then pass in a shared pointer to it. However, it's important to remember to delete myFriends explicitly to avoid memory leaks.
The above is the detailed content of When Should You Use References and When Should You Use Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!