Pointers in C

 











    For this weeks assignment I will demonstrate a technique I actually just learned this semester in one of my csc classes. It is the idea of pointers. I am currently learning about C. The interesting part about C is the concept of pointers that I did not realize we were already using in java. A pointer is a a variable that holds the memory of an address location in your memory. Instead of actually holding a value it holds a location that you can use and pass as a parameter to a function if you want to edit that variable in another function. If you were just to pass a value as a parameter the function would only get a copy of the value and if you try to edit it in the function the function that it got called from wouldnt update. I will explain what is going on in my code for an example.
    The program I wrote is dice rolling game. I only posted my main and my player turn function to show how pointers work. In C the first thing you have to do is declare your prototypes. My prototypes in my function are line 14-16. These just declare the function that I will be writing throughout my program. Since my function are written after my main this lets the compiler know that there are some functions in my program to look out for that way there is not an error during runtime. Next I initialize my player scores at 0 each. I then declare my random number generator in my main. We then declare a while loop to keep rolling our dice until there is a winner. A winner is declared when either player scores a score of 100 or more. The way the game works does not matter in this example since I am just showing how pointers work.
    In my while loop on line 30 I called my player turn function with both player1 and player2 variables. If you notice I pass the & sign on each of my variables. This allows the address of that variable to be passed instead of the actual value. That way when the address goes into my playerturn function we can update the player scores from the function if not only a copy of the values would get passed and if we edit those values in the player turn function they would not update in the main. Since we passed the address of the values now in our player turn function we can dereference the pointer and update the values in main. This is super handy as well when needing to pass objects. Sometimes objects and be really large in size and it is not good practice to pass an object of such large size as a parameter. Instead of passing the actual object we can pass the address of the object. Once we do that we can update the object by dereferencing it in the function it got passed in.
    

Comments

  1. I liked this. I am not majoring in cs, so this may seem foreign to me, but you did a great job explaining the concepts of pointers and their necessity in this program!

    ReplyDelete

Post a Comment

Popular posts from this blog

Ping Pong in Python

Sunset Views Coding Challenge

Week 9 Coding Challenges