[C++] Introduction pointers

Heitor Helmer Herzog
3 min readFeb 6, 2017

--

As you know every variable is a memory location and every memory location has it’s address defined which can be accessed. Let’s say that the figure here is computer’s memory and each block being a memory address.

Then when the program executes the computer allocates some amoung of memory corresponding to the particular variable. How much memory it allocates depends upon the datatype and also the compiler.

  • The integer variable A is allocated 4 bites of memory .
  • The chacacter variable C is allocated 1 bite of memory.
  • Which address correspond one bite.

And other variables as well. Which one is allocated some amount of space in the memory.

So like the variable int A, which we pass a value of 5 for instance, the address of A will continue to be 204 till 207 that will return the value of 5.

We can know the adreess of the variable and operate upon these memories adresses using pointers. Pointers are variables that store address of another variable.

Let’s say we have a block of 4 bites at address that stores an integer variable ‘A’ and have another variable the type of witch is pointer to intiger of name ‘P’, and this variable ‘p’ stores the address of ‘a’.

Using the properties of P or using some operators upon P we can reach A . P its’s store at location address 64 and takes 4 bites of memory.

And if we have another integer at address 208 named B and have value 10, if we change the value the addrees in P from 204 to 208, P will point to B.

Let’s see the syntax of pointer variables in C.

A normal variable is declared by writing the data type like:

  • int A.

If we want to write a pointer variable that should point another variable we put an asterisk sign before the variable like so:

  • Int * P.

To store the address of ‘A’ in ‘P’ wee need to use the statement P= &A. If we put & in front of a variable it give us the address of the particular variable.

Now, with we try to print P the value it will be 204. With we will try to print &A the value also wll be 204. And if wee try to print the value of &P ? This will give us the address P, which is 64.

There’s one more important property of pointer, if we put an asterisk sign in front of the pointer than it gives us the location that it points to. It will give us the value store from the variable A witch is 4.

We can modify the value of the variables like this:

*p =8, and so when we print the variable a the output will be 8.

--

--

Heitor Helmer Herzog
Heitor Helmer Herzog

Written by Heitor Helmer Herzog

Software developer, In love with games and the industry. Let’s code! About me: www.linkedin.com/in/heitorhherzog

No responses yet