Pointers are often used to make C programming much easier and it helps programmers improve their program's efficiency. Not only that, by using the pointer's you can achieve unlimited amount of memory usage in your program, that’s cool right.
Definitions and Uses of Pointers
Pointers are the variables that hold an address of another variable of the same data type. The cool thing about the address of a variable is that, you'll then be able to go to that address and access the data stored in it. Pointers are basically used in the C in different ways. Some of them are:
- To create dynamic and flexible data structures.
- To pass and handle variable arguments passed to functions (Call by reference).
- To retrieve information stored in list like arrays.
Pointer Variables
As I said earlier, pointers indicate the memory address of any kind of object i.e. It can be address of any primitive data types or structures or even functions. The variable which holds the address is called the pointer variable.
Typical Pointer Declarations
Let’s see how we can declare a pointer in C. Generally say integer variable “var” is declared like below.
int var;
In case of pointer for example, say integer type of pointer the declaration is like this:
int *var;
In general the declaration is like
<type> *<variable name>;
<type> *<variable name>;
That’s why it is recommended that you should always initialize a pointer value with NULL like this.
int *var = NULL;
You have noticed that "*" operator is used at declaration to denote a variable to a pointer type. Another operator "&" is used to represent the address of a variable.
int i = 10; int *p = &i;
When you declare a variable, a memory is allocated for that variable. For the above example, say the variable "i" has address 0x2000 and the address contains value 10, now when the "p" variable is declared, it also gets a memory address say 0x2100, because we have declared that it will contain address of I, so it will contain the value of 0x2000.
0x2000 ( i ) 0x2100 ( p )
No comments:
Post a Comment