Subscribe to Invariance_Under_Translation        RSS Feed
-----

Pointers

Icon Leave Comment
Alright, i went ahead and fixed an error in the dice game. I forgot to incorporate the srand() function, and without this to seed the rand() function you will continually get the same random output.

Now, on to Pointers. Pointers allow us to reference a specific block of memory that is containing a variable. To illustrate this, i will give an example:

int * pointer1;
 
int var1 = 10;
 
int var2 = 20;
 
pointer1 = &var1;



So, first we declare pointer1 as a pointer of type int. We do this by using the dereference operator *. Then we declare two variables with preset parameters.

The fourth line of code is assigning pointer1 to reference var1's location of memory. This does not assign pointer1 to have a value of 10, but rather creates a reference to the location that var1 is storing it's data. For example, if var1 is storing the value of 10 at memory block 1729, pointer1 is assigned to that block of memory. I will show you how this can be useful to us:

int * pointer1;
 
int var1 = 10;
 
int var2 = 20;
 
pointer1 = &var1;
 
*pointer1 = var2;



What we have done by adding that last line of code is change the value stored by var1 to 20. To spell out what that line of code means, we could say "The value stored at the memory address pointed to by pointer1 is equal to the value of var2."

Now that you have seen what pointers can do for our variables, lets use the same concept in an array.

int * pointer1; 
 
int array1[] = {1,2,3,4,5};
 
pointer1 = &array1[0];

*pointer1 = 3 



As you can see, be declare our pointer to be of type int, we create an array that has five pre-set variables and then we associate pointer1 to the first variable in the array.
Once this has been done, we can change the value being stored at array1[0] by pointing the value of three towards it's memory block.

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

July 2018

S M T W T F S
1234567
891011121314
151617181920 21
22232425262728
293031    

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)