The easiest way to explain pointers, and how i understood them easily, is that pointers are variables that store another variable's memory address. You can use pointers to change the values of memory on the memory address. Saying:
this can be done with pointers too! But before that, here's some syntax.
to declare a pointer, you add an asterisk after declaring the data type. Example
int *pointer;
declares a pointer that points to an integer, and
string *pointer;
declares a pointer that points to a string. Now, to manipulate the values inside the pointer, we use special syntax. Here's how to do that:
1 2 3 4 5
|
int x;
int *p_x=&x; /*i use p_ prefix to indicate that something is a pointer. Notice
the '&' sign. You can read it as 'address of' because that operator returns the memory address of a given variable. */
*p_x=5; /*Notice the asterisk. It's not because p_x is a pointer. You can read it as 'value of', because then you can edit the contents of a memory address*/
/* It's like saying 'The value on the memory address 'p_x' is 5*/
|
Now to explain the '*p_x=5;' line a bit better. 'Value of' p_x returns the value of the memory address that the pointer is pointing to. From this example, the pointer is pointing to the address of 'x'. Then we use '=' as any other time we would make a variable equal to a number. After that we don't use any other special syntax. If you didn't understand all of this, re-read it, because pointers can be a bit confusing. Don't go jumping to pointers and arrays, because that way you won't understand it as you should. This is a basic pointer explanation, but this will help you a lot. After understanding this, you can continue working with pointers.
THE USE OF POINTERS
Even if you understood what i wrote before, you might want to ask "Why would i complicate things like that? Why wouldn't i just write 'x=5;'?"
Well, here's a reason, sometimes you need to pass on a big structure or array to a function. But here's a problem-every time you use them in functions, you need to
copy the contents of the structure or array, but with pointers, you are just sending the
address of the structure. This is useful because your program will run much faster. This may not look very attractive to you right now, but it will later.
Another use of a pointer is-i'll explain it on an example. Let's say you need to declare an unknown sized array. We usually use just the biggest value possible, like 'int array[10000]', but sometimes this isn't efficient. You will learn how to do this later, because it is complicated, but it is nothing to be afraid of, and you
will learn how to use pointers properly and efficiently. I hope this helps ^_^.