Create a variable
Let's create a variable and give it a value of 3.
Variable a's info
Variable a's info
Let's create a variable and give it a value of 3.
int a; a = 3;
Variable a's info
Data Type
The data type of a variable tells you what kind of data it will hold. We can see in the code above that variable a is an int.
int = holds an integer (aka a whole number)
char = holds a single character
pointer = holds a memory address
Variable a's info
Memory Address
The a variable is stored somewhere in your computer's memory. Just like humans have an address, variables have an address too. ( 0x00008130 is just an example address, your variable will probably have a different address)Pointers
A pointer holds this memory address-- so basically it POINTS to where a variable is located.
Let's create a pointer that will point to where our a variable is located. To create a pointer, we need the data type of the variable we will be pointing to (a is an int) and then a star *. Convention is to put the star next to the variable's name on the right.
Let's set our new ptr variable to the address of a. To get the address of any variable, we just add & in front of it.
Let's create a pointer that will point to where our a variable is located. To create a pointer, we need the data type of the variable we will be pointing to (a is an int) and then a star *. Convention is to put the star next to the variable's name on the right.
int *ptr;
Let's set our new ptr variable to the address of a. To get the address of any variable, we just add & in front of it.
int a; int *ptr; a = 3; ptr = &a;
Variable a's info
Variable ptr's info
As you can see, the value of ptr is the address of a. It is POINTING to a.
Using the pointer
You can now use our variable in several different ways.
ptr = gives you the value of ptr. In this case 0x00008130.
*ptr = gives you the value of the variable ptr is pointing to. In this case, ptr is pointing to the variable located at 0x00008130, which is a. And a's value is 3.
(I remember this as I VALUE you, you're a STAR)
&ptr = as mentioned putting & in front of a variable will give you the address of that variable. In this case we would get 0x00008500.
(I remember this as "AND what's your ADDRESS?")
Comments
Post a Comment