Pointer c-1
Pointer c-1
• Syntax :-
data_type *var_name;
• Ex :-
int*p;
char*p;
Initializing of Pointer Variable
• Pointer initialization is the process of assigning address of a variable to
pointer variable . Pointer variable contains address of variable of same data
type .
• Ex :-
int a=10;
int*p; // pointer declaration
p=&a; // pointer initialization
or
int*p=&a; //declaration and initialization
together
Chain Of Pointer
• It is possible to make a pointer to point to another
pointer, thus creating a chain of pointers.
• Syntax:-
data_type * ptr=expression;
y=*p1 * *p2
sum=sum+*p1;
*p2=*p2+10;
Rules of Pointer Operations
• A pointer variable can be assign the address of another vaiable .
• Here,
pointer_type: Type of data the pointer is pointing to.
array_name: Name of the array of pointers.
array_size: Size of the array of pointers.
Array Of Pointer to Character
•c = * cp++ or c = * (cp++)
assigns the value pointed to by cp to c, and then increments the pointer
cp.
• c = ++*cp or c = ++(*cp)
increments the value pointed to by cp, and then assigns the new value
to c; cp remains unchanged
•c = (*cp) ++
fetches the value pointed to by cp, assigns it to c, and then increments
the value pointed to by cp;
• c = *--cp or c = * (--cp)
decrements the pointer cp, and then assigns the value
pointed to by cp to c.
•c = * cp-- or c = * (cp--)
assigns the value pointed to by cp to c, and then
decrements the pointer cp.
• c = -- *cp or c = -- (* cp)
decrements the value pointed to by cp, and then assigns
the new value to c; cp remains unchanged
•c = (* cp) --
fetches the value pointed to by cp, assigns it to c, and then
decrements the value pointed to by cp; cp remains unchanged.
• Write a C program to traverse an array using pointer arithmetic
Pointer Conversion
• A pointer of one type can be converted to a pointer of another type by using
an explicit cast. The cast (T *) converts its operand into a pointer to an object of
type T.
•In such situations, the type void * is used as the proper type for a generic
pointer.
• Any pointer may be converted to type void * and back without loss of
information.
• An explicit cast for such conversion may be added for clarity, but is not
necessary.
• A function can take a pointer to any data type as argument and can return a
pointer to any data type.
•For example:
double *maxp(double *xp, double *yp)
{
return *xp >= *yp ? xp : yp;
}
•This function definition specifies that the function maxp returns a pointer to a .
double object, and expects two arguments, both of which are pointers to double
objects.
•makes mp point to v.
• For example :
void exchange(int *ip, int *jp)
{
int t;
t = *ip;
*ip = *jp;
*jp = t;
}
• and that the values of the integer variables i and j are 1 and 2, they
become 2 and 1 respectively after the function call exchange (&i,
&j)
• Application Of Array Of Pointers :-
1. Dynamic allocation of memory.
2. Handling string
3. Function Pointers
3. Performance overhead