A pointer in C is the address of variable
of a function. The advantages of a pointer over using normal variables are:
If you pass the pointer to a variable to a
function, then that function can modify the value of the variable directly.
Pointer
variables can also be used in arithmetic expressions. The following operations
can be carried out on pointer:
1.
Pointers can be incremented or
decremented to point to different locations like
ptr1=ptr2+3;
ptr++;
--ptr;
2.
If ptr1 and ptr2 are properly
declared and initialized pointers, the following operations are valid.
res=res+*ptr1;
*ptr1=*ptr2+5;
prod=*ptr1**ptr2;
quo=*ptr1/*ptr2;
3.
Expressions like
ptr1==ptr2,ptr1<ptr2 and ptr2!=ptr1 are permissible provided the pointers
ptr1 and ptr2 refer to same and related variables. These comparisons are common
in handling arrays.
A block of memory may
be allocated using the function malloc. The malloc function reserves a block of
memory of specified size and returns a pointer of type of void. This means that
we can assign it to any type of pointer. It takes the following form:
ptr=(cast-type *) malloc(byte-size);
ptr is a pointer
of type cast-type. The malloc returns a
pointer to an area of memory with size byte-size
Example:
x=(int
*) malloc(100 *sizeof(int));
No comments:
Post a Comment