Introduction to Pointers Pointers are regarded as one of the
most difficult topics in C. Although they may appear as little confusing for a
beginner, they are most powerful tools and are used frequently with aggregate
types, such as arrays and structures. In fact, real power of C lies in the
proper use of pointers. Here, we consider only the introductory study of
pointers and we shall discuss them in detail in unit-III. Since addresses of
variables are not guaranteed to be represented in the same fashion as integers,
therefore to store addresses, we need a special type of variable, called a
pointer variable. So a pointer variable is another variable that holds the
address of the given variable to be accessed. Thus pointers provide a way of
accessing a variable without referring to variable directly. To declare a
pointer variable, we precede the variable name with an asterisk (∗). The declaration has the form type
∗pt_name;
Where ‘type’
is the pre-defined or user-defined data type and indicates that the pointer will
point to the variables of that specific data type.
For example,
the statement
int ∗ x;
declares the
variable x as a pointer variable that points to an integer data type. It should
be noted that the type ‘int’ refers to the data type of the variable being
pointed to by x and not the type of the value of the pointer.
Similarly,
the statement
float ∗ y;
declares y as a pointer to a floating-point variable. 40
Programming in C 8.1.
Initializing a Pointer : Once a pointer
variable has been declared, it can be made to point to a variable by using an
assignment statement as x = & pay; which causes x to point to ‘pay’ i.e. x
none contains the address of pay. This is known as pointer initialization. A
pointer should be initialized before use. We should also ensure that pointer
variables always point to the corresponding type of data.
For example,
float a, b;
int x, ∗y;
y = & a;
b = ∗ y;
will give
wrong results. Further, assigning an absolute address to a pointer variable is
prohibited.
Thus
int ∗ x;
x = 237;
is invalid. A pointer variable can be
initialized in its declaration itself.
For example
int x, ∗p = & x;
is valid. It declares x as an integer variable
and p as a pointer variable and then initializes p to the address of x. Note
carefully that this is an initialization of p, not of ∗p. Further, the target variable x is declared
first.
Thus, the statement
int ∗p = &x,
x; is not valid.
No comments:
Post a Comment