Sunteți pe pagina 1din 27

POINTERS

Advantages of Pointers
• Pointers provide direct access to memory
• Pointers provide a way to return more than one value to
the functions
• Reduces the storage space and complexity of the
program
• Reduces the execution time of the program
• Pointers allows us to perform dynamic memory
allocation and deallocation.
• Pointers helps us to build complex data structures like
linked list, stack, queues, trees, graphs etc.
• Pointers allows us to resize the dynamically allocated
memory block.
• Addresses of objects can be extracted using pointers
Declaration of pointers
• Pointer variable declaration follows almost similar
syntax as of normal variable.
• Pointer declaration is similar to other type of
variable except asterisk (*) character before
pointer variable name.
Syntax to declare pointer variable:
data-type * pointer-variable-name;
• data-type is a valid C data type.
• * symbol specifies it is a pointer variable.
• pointer-variable-name is a valid C identifier i.e.
the name of pointer variable.
Let's consider with following example statement
int *ptr;
Here, in this statement
• ptr is the name of pointer variable (name of
the memory blocks in which address of
another variable is going to be stored).
• The character asterisk (*) tells to the compiler
that the identifier ptr should be declare as
pointer.
• The data type int tells to the compiler that
pointer ptr will store memory address of
integer type variable.
• Finally, ptr will be declared as integer pointer
which will store address of integer type variable.
• Pointer ptr is declared, but it not pointing to
anything; now pointer should be initialized by the
address of another integer variable.
• Consider the following statement of pointer
initialization
int x;
int *ptr;
ptr=&x;
Here, x is an integer variable and pointer ptr is
initiating with the address of x.
Accessing address and value of x using pointer
variable ptr
• We can get the value of ptr which is the
address of x.
• ptr will print the memory address of x.
• *ptr will print the value which is stored at the
containing memory address in the ptr (value of
variable x).
Here is the simple example to demonstrate
pointer declaration, initialization and accessing
address, value through pointer variable:
#include <stdio.h>
void main()
{
int x=20; //int variable
int *ptr; //int pointer declaration
ptr=&x; //initializing pointer
printf("Memory address of x: %p\n",ptr);
printf("Value x: %d\n",*ptr);
getch();
}
Output:
Memory address of x: 0x7ffe64f5c814
Value x: 20
Pointer Expressions
Like other variables pointer variables can be used in
expressions.
1) If p1 and p2 are declared and initialized pointers, then
the following statements are valid:
Y=*p1**p2;
Sum=sum+*p1;
Z=5*(-(*p2)/ *p1);
*p2=*p2+10;
*p1=*p1+*p2; *p1=*p2-*p1;
NOTE: in the third statement there is a blank space
between ‘/’ and * because the symbol /*is considered as
beginning of the comment and therefore the statement
fails.
2) if p1 and p2 are properly declared and initialized
pointers then, ‘C’ allows adding integers to a pointer
variable.

EX:
int a=5, b=10;
int *p1,*p2;
p1=&a;
p2=&b;

Now,
P1=p1+1=1000+2=1002;
P1=p1+2=1000+ (2*2) =1004;
P1=p1+4=1000+ (2*4) =1008;
3) If p1 & p2 are properly declared and initialized,
pointers then
‘C’ allows to subtract integers from pointers. From
the above example,
P1=p1-1=1000-2=998;
P1=p1-2=1000-4=996;
4) “Subtraction of one pointer from another pointer
is also possible".
NOTE: this operation is done when the both pointer
variable points to the elements of the same array.
EX:
P2- P1 (It gives the number of elements between p1
and p2)
• We can not perform addition, multiplication
and division operations on two pointer
variables.
• For Example:
ptr1 + ptr2 is not valid
• We can not perform addition, multiplication
and division operations on two pointer
variables.
• For Example:
ptr1 + ptr2 is not valid
5) Pointer can also be used with increment and decrement
operators.
Ex:
int a=10;
int *b;
b=&a;
• We can use increment and decrement operator along
with pointer variable to increment or decrement the
address contained in pointer variable.
• Example:
ptr1++;
ptr2--;
6) We can use relational operators to compare pointer
variables if both pointer variable points to the variables of
same data type.
Functions and pointers
Call by reference:
• Pointer as a function parameter is used to hold
addresses of arguments passed during function
call. This is also known as call by reference.
• When a function is called by reference any
change made to the reference variable will effect
the original variable.

#include <stdio.h>
void swap(int *a, int *b);
int main()
{ int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n);
printf("After Swapping:\n\n");
printf("m = %d\n", m); printf("n = %d", n);
return 0; }
/* pointer 'a' and 'b' holds and points to the address of 'm' and 'n' */
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
function can also return a pointer to the calling
function. In this case you must be careful,
because local variables of function doesn't live
outside the function. They have scope only
inside the function. Hence if you return a
pointer connected to a local variable, that
pointer will be pointing to nothing when the
function ends.
#include <stdio.h>
int* larger(int*, int*);
void main()
{ int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y) return x;
else return y;
}
Safe ways to return a valid Pointer.
• Either use argument with functions. Because
argument passed to the functions are
declared inside the calling function, hence
they will live outside the function as well.

Or, use static local variables inside the
function and return them. As static variables
have a lifetime until the main() function exits,
therefore they will be available througout the
program.
• Pointer to functions
• It is possible to declare a pointer pointing to a function.
A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
• Here is an example :
int (*sum)();
A function pointer can point to a specific function when it
is assigned the name of that function.
int sum(int, int);
int (*s)(int, int);
s = sum;
• Here s is a pointer to a function sum. Now sum can be
called using function pointer s along with providing the
required argument values.
• s (10, 20);
Call by value
• The call by value method of passing
arguments to a function copies the actual
value of an argument into the formal
parameter of the function.
• In this case, changes made to the parameter
inside the function have no effect on the
argument.
• It means the code within a function cannot
alter the arguments used to call the function.
Consider the function swap() definition as
follows.
• void swap(int x, int y)
• {
• int temp; temp = x;
• x = y;
• y = temp;
• return;
• }
• Now, let us call the function swap() by passing
actual values as in the following example −
#include <stdio.h>
void swap(int x, int y);
int main ()
{
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100
After swap, value of b :200 It shows that there are no changes in the values, though
they had been changed inside the function.
Pointer to Array
• We can use a pointer to point to an array, and then we
can use that pointer to access the array elements. Lets
have an example,
#include <stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as
int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p); p++;
}
}
The pointer *p will print all the values stored in the array one
by one.
Array of Pointers
• We can also have array of pointers. Pointers are
very helpful in handling character array with rows
of varying length.
• char *name[3] = { "Adam",
"chris",
"Deniel" };

• //Now lets see same array without using pointer


• char name[3][20] = { "Adam",
"chris",
"Deniel" };
In the second approach memory wastage is
more, hence it is prefered to use pointer in such
cases.
Double Pointer (Pointer to Pointer)

• The first pointer is used to store the address of


the variable.
• And the second pointer is used to store the
address of the first pointer.
• That is why they are also known as double
pointers.
• We have to place an additional ‘*’ before the
name of pointer to declare double pointer.
Syntax:
int **ptr; // declaring double pointers
void main()
{
int var = 789;
// pointer for var
int *ptr2;
// double pointer for ptr2
int **ptr1;
// storing address of var in ptr2
ptr2 = &var;
// Storing address of ptr2 in ptr1
ptr1 = &ptr2;
// Displaying value of var using both single and double pointers
printf("Value of var = %d\n", var );
printf("Value of var using single pointer = %d\n", *ptr2 );
printf("Value of var using double pointer = %d\n", **ptr1);
}

S-ar putea să vă placă și