28-09-2013, 01:26 PM
Pointers in C
Pointers .ppt (Size: 386.5 KB / Downloads: 16)
Variable
A variable is a named memory location.
Variables provide direct access to its memory location.
A variable has a name, an address, a type,and a value:
"the name identifies the variable to the programmer
"the address specifies where in main memory the variable is located
What is a variable?
"the type specifies how to interpret the data stored in main memory and how long the variable is
"the value is the actual data stored in the variable after if has been interpreted according to a given type
Pointer variable
A pointer is a variable that contains the memory location of another variable.
Syntax:-
type * variable name
You start by specifying the type of data stored in the location identified by the pointer.
The asterisk tells the compiler that you are creating a pointer variable.
Finally you give the name of the variable.
Address operator:
Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example:
ptr=#
This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.
Manipulating Pointer Variable
Once a variable is declared, we can get its address by preceding its name with the unary & operator, as in &k.
We can "dereference" a pointer, i.e. refer to the value of that which it points to, by using the unary '*' operator as in *ptr
Constant Pointer
Constant pointer means the pointer is constant. Constant pointer is NOT pointer to constant.
For eg:
int * const ptr2 indicates that ptr2 is a pointer which is constant. This means that ptr2 cannot be made to point to another integer.
However the integer pointed by ptr2 can be changed.
Pointer to constant
Pointer to constant is
const int * ptr1 indicates that ptr1 is a pointer that points to a constant integer. The integer is constant and cannot be changed. However, the pointer ptr1 can be made to point to some other integer.
Generic pointers
When a variable is declared as being a pointer to type void it is known as a generic pointer.
Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced.
It is still a pointer though, to use it you just have to typecast it to another kind of pointer first. Hence the term Generic pointer.