Friday, November 25, 2011

Learn C++ Programming Tutorial Lesson 5 - Pointers


What is a pointer?

A pointer is a variable that holds a memory address. It is called a pointer because it points to the value at the address that it stores.

Using pointers

If you want to declare a pointer variable you must first choose what data type it will point to such as an int or a char. You then declare it as if you were declaring a variable in the normal way and then put a * in front of its name to show that it is a pointer. Here is an example of how to declare a pointer to an integer.

int *pi;
You can store the address of another variable in a pointer using the & operator. Here is an example of how to store the address of variable called i in the pointer called pi.
int i;
int *pi;
pi = &i;

You must dereference a pointer to get the value at the memory location that the pointer points to. You use the * operator to dereference a pointer. Here is an example of how we first set the value of i to 5 and then set its value to 7 by dereferencing the pointer.
int i = 5;
int *pi;
pi = &i;
*pi = 7;
cout << i;

new and delete

The new operator is used to allocate memory that is the size of a certain data type. It returns a pointer to the address of the newly allocated memory. Here is an example of how to allocate memory for an integer and then set its value to 5.
int *pi;
pi = new int;
*pi = 5;

The delete operator deallocates memory. You need to deallocate the memory for all the memory that you have previously allocated before exiting the program or else you will have memory leaks.
int *pi;
pi = new int;
*pi = 5;
delete pi;

Typed and untyped pointers

We have been using typed pointers so far because they point to a specific data type. An untyped pointer can point to anything. You declare an untyped pointer as the data type void.
void *up;

malloc and free

The malloc command allocates a certain number of bytes and returns a pointer to the first byte. You must use the free command to deallocate the memory that was allocated with malloc. To be able to use malloc and free you must include the malloc header file. Here is an example that allocates 100 bytes of memory and stores the address of it in the pointer called up and then deallocates the memory.
#include<malloc>
...
void *up;
up = malloc(100);
free(up);

0 comments:

Post a Comment

Setec Institute || Group : SH6 | | Name : Kim Chanthy. Powered by Blogger.

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hot Sonakshi Sinha, Car Price in India