Thursday, November 24, 2011

Learn C programming tutorial lesson 5 - Pointers

What are pointers

A pointer is a variable that holds a memory address. Because it holds a memory address it is said to be pointing to the value at that memory location. You can use a pointer in a certain way to get the value at the address to which it points.
Pointers can be either typed or untyped. A typed pointer points to a particular variable type such as an integer. An untyped pointer points to any data type....


To declare a pointer you must put a * in front of its name. Here is an examaple of how to declare a pointer to an integer and an untyped pointer:
int main()
{
   int *p;
   void *up;
   return 0;
}

You can put the address of an integer into a pointer to an integer by using the & operator to get the integer's address.
int main()
{
   int i;
   int *p;
   i = 5;
   p = &i;
   return 0;
}

You can access the value of the integer that is being pointed to by dereferencing the pointer. The * is used to dereference a pointer. Changing the value pointed to by the integer will change the value of the integer.
int main()
{
   int i,j;
   int *p;
   i = 5;
   p = &i;
   j = *p; //j = i
   *p = 7; //i = 7
   return 0;
}

Using pointers in the above way is just a long way of saying j = i. You will find out about much more useful ways to use pointers later on but for now it is only important that you have a basic idea of how they work.

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