I'm an experienced programmer, but not with C. I've spent far too long on this already, hopefully someone can point out what I'm doing wrong. I've been given the following requirement:
void do_action(obj *Queue);
I need to do some action on a queue which is in memory. Given the above, I need to call the function with an address so I can operate on it in memory instead of locally. This gives something like:
1 2 3 4 5 6 7 8 9 10 11 12 13
void do_action(obj *Queue);
main(){
// create queue
do_action(&Queue);
}
void do_action(obj *Queue){
// do the action
// now the original Queue is modified
}
I've got the action part figured out, I just am not getting how to have it affect the outside object instead of locally. After doing the work on the local copy can I overwrite the outside version with the local copy? Or do I need to operate on the outside version to begin with? If so, how? It's similar to a homework assignment, so I'm trying to not publish the solution, I'm just looking for the right concepts since it's really just an issue with the language I'm having.
I just am not getting how to have it affect the outside object instead of locally
You're not getting it because you're assuming that there's two objects. There's just one.
Consider the function as a carpenter. When you pass something by value, you're giving him a version of, say, a table and letting it work on it. The problem is that you have to move the table to and from his workshop.
On the other hand, passing by pointer (like your code is doing) is like giving him an address and saying "there's a table in that house. Do your work on it." You can give him the address to your house and avoid having to move anything.
If you were passing by value, the code would look like this:
Well don't I have to deference Queue to affect it?
Right now the code does what I want on Queue, but outside of the function my changes are lost. Calling my view function shows the correct result within the function, but calling the view function outside shows an incorrect result.
Here's my queue:
Queue: [1] [2] [3] [4]
This is what I see when I call a show function in main.
Then I call do_action. Within do_action it correctly shows the result.
Queue: [2] [3] [4] [1]
As soon as I go back to main the show function gives: