Pointer
is a variable that points to or references a memory location in which data is
stored. This means that a pointer holds the memory address of another variable.
Put another way, the pointer does not hold a value in the traditional sense;
instead, it holds the address of another variable. A pointer "points
to" that other variable by holding a copy of its address. Because a
pointer holds an address rather than a value, it has two parts. The pointer
itself holds the address and that address points to a value.
Pointer
declaration is shown below. 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.
Data-type *variable-name
Such a variable is called a pointer variable. When we
define a pointer variable we do so by preceding its name with an asterisk. In
C, we also give our pointer a type which, in this case, refers to the type of
data stored at the address we will be storing in our pointer. For example,
consider the variable declaration:
int *ptr;
int k;
ptr is
the name of our variable (just as k is the name of our integer variable). The '*' informs the compiler that we want a
pointer variable. The int says that
we intend to use our pointer variable to store the address of an integer.
Referencing
means taking the address of an existing variable (using &) to set a pointer
variable. In order to be valid, a pointer has to be set to the address of a
variable of the same type as the pointer, without the asterisk. For example in
following code p1 references c1 as shown
int c1; int *p1; c1 = 5; p1 = &c1;
Dereferencing
means accessing the variable value stored at a memory address. It is also
called as indirection operator. For example in following code p dereferencing i as shown below
int i = 5; int *p; p = &i;
*p = 7; //*p returns the variable stored at the memory
address stored in p, which is
i. i is now 7
|
Pointers like call-by-reference
also can be used to modify one or more variables in the caller or to pass
pointers to large data objects to avoid the overhead of passing the objects by
call-by-value. We can use pointers and the indirection operator to simulate
call-by-reference. When calling a function with arguments that should be
modified, the addresses of arguments are passed. This is accomplished by
applying the address operator (&) to the name of the variable whose value
will be modified as shown in following code:
Comments
Post a Comment
if you have any confusion then ask hear.