POINTERS
A pointer is a variable which holds the memory address of
another variable.
Pointer
Declaration: As similar to an ordinary
variable, pointer variables must be declared before they are using. A pointer variable is declared by preceding
its name with an asterisk * symbol. The
symbol indicates that the variable is a pointer variable. The general format of declaring a pointer
variable is:
Syntax: datatype *ptrvariable;
Where,
Ø ptrvariable is name of the
pointer variable that follows same rules as a valid identifier.
Ø ‘*’ tells the compiler that
ptrvariable is a pointer variable.
Ø datatype is the type of the
data that the pointer is allowed to hold the address.
Example: int *ptr1;
Here, ptr1 is a pointer variable that can points to an integer type variable.
Example: float *ptr2;
Here, ptr2 is a pointer variable that can points to a float type variable.
Example: char *ptr3;
Here, ptr3 is a pointer variable that can points to a character type variable.
Example: int *ptr1; float
*ptr2; char *ptr3;
2 bytes 2
bytes 2 bytes
ptr1 ptr2 ptr3
Note: Any type of pointer occupies only 2 bytes of memory. Since, pointer holds address of the variable
which is always an unsigned integer.
Initializing
Pointers: Once a pointer variable has been
declared, it can be initialized using an assignment operator as:
Syntax: ptrvariable = &ordinaryvariable;
Example: ptr = &x;
Where, x is an ordinary
variable.
Here, address of the variable
x is stored in ptr. With this, a link is
formed from pointer variable to ordinary variable.
Example: int
x,*ptr;
x=10;
ptr=&x;
A pointer variable can also
be initialized at the time of its declaration itself.
Example: int x, *ptr = &x;
No comments:
Post a Comment