dimanche 16 octobre 2011

Pointers

Pointers is such a difficult concept for beginners. Back when I started learning C, I was never able to understand them, not until I've read countless tutorials about them. So I'll try to explain them for anyone who will face the same issues as me. You already know what variables are and what we use them for. Let's take the example of the city you live in.  It's a mixture of houses, and different kinds of buildings. Our variables here are the buildings.

int my_var;  

Every building has an address. Likewise, every variable has an address in memory.

/** we can access the address of a variable in memory using &my_var

to print this value, we have to use %p in printf to print an address*/  

printf("the variable my_var  has the address: %p ", &my_var);

So what's a pointer, a pointer is also a variable. A variable which contains the address in memory of another variable. How do we illustrate this concept in our city. Suppose you want to send a postcard to your friend. In order for that postcard to reach its destination, you have to write the address of your friend. So a pointer in real life is that postcard. A pointer could be also, a direction sign pointing to your city. So when someone needs to get to your city, he has to "ask" that pointer. In C, some functions, the functions that take a pointer as parameter need to "ask" the pointer to know the value of the variable they point to.

/** declaring a pointer is pretty straightforward, you just give him the type of the variable he needs to point to, and the variable he points to */

int my_var = 7;

int *pointer_to_my_var = &my_var;

printf("the value of my_var is: %d", *pointer_to_my_var);

printf("the address of my_var is : %p", pointer_to_my_var);


To access the variable my_var using the pointer we have to use *, which is also called the indirection operator. Therefore, you should be careful, as you can see, it's not *pointer_to_my_var that contains the address of my_var, but pointer_to_my_var. So the following declaration is equivalent to the previous one.
int my_var = 7;

int *pointer_to_my_var ;   

pointer_to_my_var = &my_var ;


Ok, so what about functions that take as parameter a pointer.
int add(int * x, int * y) {

     return *x + *y;

}

//to call that function we have two methods

int x=7;

int y=9;

//we use the address of the variable directly

add(&x, &y);

// or declare a pointer to x and to y and pass them to the function

int *pointer_to_x=&x;

int *pointer_to_y = &y;

add(pointer_to_x, pointer_to_y);


That's what I called earlier asking the pointer to know the value of the variable it points to, it's like the postman read the address on your postcard so that he could deliver the postcard to your friend.

Aucun commentaire:

Enregistrer un commentaire