Tutor HuntResources C Plus Plus Resources
Understanding C Language Pointer
C Language
Date : 29/11/2016
Author Information
Uploaded by : P K
Uploaded on : 29/11/2016
Subject : C Plus Plus
Pointer
Pointers are special
variables in C used to store address of another variable of matched data-type. Pointers (or Pointer variables)
are created in the same way as an ordinary variable however the identifier must
be prefixed with an asterisk (or start) mark. Pointers are useful to
provide indirect access to the variable to which it points. Example: int *p float
*q char
*r Unlike ordinary variables,
system allocates equally 2 bytes of memory to each pointer irrespective to
their data-type. That is, an integer pointer occupies 2 bytes as well as a
float pointer occupies 2 bytes as other pointer too. NOTE: Pointers are always unsigned
in nature because the addresses are always sign-less data (memory location
numbers). Diagrammatically, Let us take a variable and a pointer for it as- int a=50 int
*p p=&a // Address of a is assigned to pIn the above example system
allocates 2 bytes memory to the ordinary integer variable a (let it is the
location number 2001-2002 as given in the diagram). Similarly, pointer p also
occupies 2 bytes (let it is the location number 4001-5002 as given in the above
diagram). Now while the pointer is assigned with address of the variable a,
it would now contain 2001. IMPORTANT: If a pointer is
assigned with the address of a variable of unmatched data-type or incompatible
type, system generates an error. Example: int a=50 float
b=2.5 and int *p float
*qNow if we assign p=&b or q=&a both are illegal Similarly, we can t assign
data or a variable of ordinary type to a pointer because pointers are only
meant for storing address. Example:Suppose there are variables
and pointer in a program like int x char y float z int *m char *n float *o m=x //
Is not legal because x contains a value and pointers are to store address. m=&x // Ok Again, m=&z // Not legal because `z` is a float variable but `m` is an
integer pointer. o=&z // Ok. Generally, a variable has
two pieces of information its content (value) and its address. But pointers
provide 3 pieces of information. Along with its content (address of the
variable to which it points) and its address pointers has de-referenced value.
The de-reference value of the pointer (or indirection value) is the value in
the variable to which it points. We can get indirection or
de-reference value of a pointer through unary indirection (*) operator. Example: int a=50 int
*p p=&a Now, printf( %d , *p) // Displays value of a Or, *p=100 // Changes variable a NOTE: * is used for two
purposes First, to declare the pointer and Second, to get the indirection
data. Asterisk operator is also used as binary multiplication operator. System
automatically evaluates the meaning of the operator according to its use (i.e.
whether it is used as unary or binary).
This resource was uploaded by: P K