L34rn teh C++ Lesson 6

Cunbelin

Newbie
Joined
Aug 3, 2003
Messages
281
Reaction score
0
Lesson 6

MB I MAK GAME NOW ?



Ok so we have covered loops conditionals, variables, and functions, we are going to concentrate on a new type of variable for this lesson, the pointer. Ok first thing though we have to get something about functions out of the way, every function has it's own set of variables and while the code for the functions is stored in memory when we first start the program(after all it doesn't change), the variables are not, they are only stored in memory when we call the function, to do this we have a special structure called "the stack" the stack pretty much works like a stack, so we can only access the top item, the last item placed there. The stack is used when we call functions, each time we call a function we add a layer to the stack filled with all the variables that are used in that function. When we are finished with the function, those variables go away never to be seen again, the only one that can be saved is the return value, and that is returned to the previous layer. When a function is called we consider it to be "in scope" this means that all it's variables can be used, the function that called our function is not in scope and therefore we can't use it's variables. This allows us to have the same variable name in our code, as long as they are in different functions. You may have noticed this with our calculator program already. The main advantage of this system is that we use as little memory as possible, it allows us to use consistent naming schemes, makes calling a function within a function simpler, and allows us to call the function that was called (recursive loops).



Now this doesn't really matter to you at this point, what does matter is you can't change any values outside of your function's scope, and that sucks. So enter the pointer. Pointers allow us to pass not the value inside the variable, but rather the location of the variable (remember variables are their address and their size) and so we know where to look even if it is outside our scope. So what we are talking about here is a type that stores the locations of variables, every type in C++ has an equivalent pointer even pointers have equivalent pointers(and so on)! Pointers are very similar to variables except their value is actually an address to a real variable. Pointers themselves are actually exactly the same, they all store a number, and unless you are using a 64 bit platform, they store their value in four boxes(bytes). Pointers are required to be typed, because unlike a variable that knows both the address and size of the data, pointers only store the address as their value, so we have to give the pointer a type so we know how many boxes are included in the address. Are you confused yet ? Another way to look at pointers is just what the name implies, that they are pointing to something. Alright we are going to return to pointers alot but lets get on with a bit of code showing how to create pointers and assign them:



PHP:
#include <iostream.h>

int main ()
{
	int an_int;
	int* an_int_pointer;
	an_int = 7;
	an_int_pointer = &an_int; // new operator here the address operator
				  // this evaluates to the address of an_int
	cout << an_int;
	cout << "\t";
	cout << an_int_pointer;	 //just like ints you can print pointers but it prints the value
        cout << "\n";
	cout << *an_int_pointer; //Another new operator the dereference operator
				 //this operator works the oppisite way of the address
				 //operator and gives the value an_int_pointer is pointing at
	return 0;
}

Ok so I used two new operators there, the * and the & operator these are two operators used when working with pointers, the * operator is used to look at the address stored in the pointer, so it makes it like a normal variable. The & operator works in the opposite way it evaluates to the address of whatever is on the right of it. To note you will often find pointers declared in this manner as well:
int *an_int_pointer;
I personally prefer the * to the left because it is part of the type not an indirection operator or part of the name. Ok so now you can make a pointer out of any type, you just have to add a star to it, you can even make a pointer to a pointer type:
PHP:
#include <iostream.h>

int main ()
{
	int an_int;
	int* an_int_pointer;
	int** an_int_pointer_pointer;
	an_int = 7;
	an_int_pointer = &an_int;
	an_int_pointer_pointer = &an_int_pointer;

	cout << an_int;
	cout << "\t";
	cout << an_int_pointer;
        cout << "\n";
	cout << *an_int_pointer;
	cout << "\t";
	cout << an_int_pointer_pointer; //this prints the address of an_int_pointer
	cout << "\n";
	cout << *an_int_pointer_pointer;//prints the value of an_int_pointer
	cout << "\t";
	cout << **an_int_pointer_pointer; //prints the value an_int_pointer points to.
	return 0;
}

Now if you have run these you will have noticed the odd values printed for addresses, these are hex values, they are the same as normal numbers, at the end of this lesson I will give you a quick guide on how to read them. Hex values are used to specify memory addresses, you may remember them from HTML coloring if you are familiar with HTML. Alright that is about it for today, tomorrow we are going to take a look at Arrays, and expand on pointers. I know today was short, but you really have to understand pointers, it is absolutely vital, try doing things with multilevel pointers(pointers to pointers are 2 level pointers). If you like, you can try to do this concept visually by drawing variables as squares, and pointers with squares and an arrow pointing to a variable.
 
Ok you know how to count to 16 right ? well think for a second what if instead of counting to 10, we counted to 16, and instead of 10 11 12 13 14 and 15, we used A, B, C, D, E, F, if you can do that, you can do hexadecimal numbers. Simply put each place can go up to 15 or F instead of going up to 9. So FF, would be the same as 255, or 1A would be the same as 16(the 1) and 10, or 26. And that is basically hexadecimal numbers.
 
hehe..nice, i'll deal with it if i have got some time..pointers are still my personal enemys o_O
 
It took me 3 months to learn pointers.

WOW it was a hard time, but thanks for the code its usefull for learners.
 
Since I have alot of trouble getting the concept of pointers.. would you say this is somewhat correct?

*int
the VALUE of the data at MEMORY ADRESS int

&int
the MEMORY ADRESS of the value(s) of int?
 
*int
the VALUE of the data at MEMORY ADRESS int

&int
the MEMORY ADRESS of the value(s) of int? [/B][/QUOTE]

Yep.

Or more exactly, &int this the memory address of where data stored in the int variable would go.

Btw, as int is a reserved word, you couldn't use it as a variable name (but i guess you knew that).
 
i believe he was just saying a pointer to an integer and a reference to an integer, not using it as a variable name.
 
I'm not very experienced at c++ but hardly a newbie, I've written small programs like logparsers but I just couldn't grasp the pointer concept..
 
Originally posted by rootbin
i believe he was just saying a pointer to an integer and a reference to an integer, not using it as a variable name.

Just making sure, could have been confusing to some possibly otherwise. I guessed he already knew that. :)
 
what's so complicated about pointers? it just points to something...
 
I have a degree in comp sci, and pointers weren't such a horrible deal. All you need to remember is:
*ptr = whatever is in what ptr is pointing to
ptr = a pointer to an object
ptr->data = a data member belonging to the object being pointed at by ptr

&obj = address of obj

once you have that, doing arrays of pointers and lists/trees etc.. is a breeze... just gotta keep track of what you do. Actually, pointers make things easy to manage/manipulate!

Seriously, people have panic attacks over simple pointer arithmetic etc... What is hard to understand is the wording of instructors/books. A friend of mine changed majors because he wouldn't relax when it came to pointers.

I dont mean to be condescending though, i know it seems that i do... I guess i'm in denial about pointers :D. Best way to learn is to try things out in little 10 line programs and you will be surprised.
 
Originally posted by mrBadger
^ Oh dear.

I'm assuming you aren't a programmer


actually, they're just that simple. people just make them difficult for themselves.
 
I guess then if you read it in a book or something it seems complicated. if you take it in a unviersity .. well there everything is complicated so pointers aren't such a big deal :p j/k
they are probably easier if you study them in some sort of a school rather than read a book or an online tutorial. just my guess.
 
Yeah, well, I am learning from a book, and then moving on to a proper course. :)
 
OK.... He is right... a pointer is just a variable that holds the address of some object in memory. Thats it.

Think of speed dial. You program the number of a plumber into button 1. When you want to call the plumber, you press button 1. You don't care anymore what the number is, you just press it. This is a lot faster then actually going down to the business and talking to the plumber right?

Well, the number you program into the phone is the address of the memory, and button 1 is the pointer.

Most people get confused when they are introduced to pointers because they don't know how or why they should be using them. I mean, why not just create the variables by hand right? All they see is this:

int num = 12;//local scope variable num
int* pointer1 = &num;//assign the address of num to the pointer
*pointer1++;//increment the value that pointer1 points to
cout<<*pointer1;//would output 13
cout<<pointer1;//would output the address of num
//so what?!!!

Well, pointers are most often used in a data structures. If you don't know what a data structure is, think of a phone book.. it has all those numbers that you can call. It doesn't contain the people or places that the numbers represent, (because then the phone book would be about the size of the planet, and thats just dumb.) When you pick up the phone book to find a pizza place to order a pizza, you don't care WHERE on the planet the pizza place is located, you just want this pizza, right?

The memory in the computer is the same. When you create a new object in memory, you get the address of it in return. You don't really care where in memory it gets created (well, thats not ALWAYS true, but for the most part it is). if you lost the address, then the memory you created is gone. Well, not gone to the computer, but gone to YOU. If you got some hotties number, and you lost it, she would still exist but you would have no way of contacting her. The same goes for the memory you created. This is called a memory leak becasue you have NO WAY of accessing that memory again. So to avoid this, you store that info in a pointer, and stash the pointer in the phone book, or data structure, so you can retrieve it later.

Pointers are the base for polymorphim. Its why we program c++ instead of c.
 
Back
Top