Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

POINTERS

INTRODUCTION
• A pointer is a derived data type in C.
• Pointers contain memory addresses as their values.
• Since these memory addresses are the locations in
the computer memory where program instructions
and data are stored, pointers can be used to access
and manipulate data stored in the memory.
POINTERS BENEFITS TO THE
PROGRAMMER
• Pointers are more efficient in handling arrays and data tables.
• Pointers can be used to return multiple values from a function via
function arguments.
• Pointers permit references to functions and thereby facilitating passing of
function as arguments to other functions.
• The use of pointers arrays to character stings results in saving of data
storage space in memory.
• Pointers allow C to support dynamic memory management.
• Pointers provide an efficient tool for manipulating dynamic data
structures such as structures, linked lists, queues, stacks and trees.
• Pointers reduce length and complexity of programs.
• They increase the execution speed and thus reduce the program
execution time.
UNDERSTANDING POINTER
• The computer’s memory is a
sequential collection of storage cells
• Each cell. Commonly known as a byte,
has a number called address
associated with it
• The address are numbers
consecutively, starting from zero
• The last address depends on the
memory size
• A computer system having 64K
memory will have its last address as
65,535
POINTER VARIABLE
• We may access the value 547 by using either the
name X or the address 4000.
• Since memory addresses are simply numbers, they
can be assigned to some variables, that can be
stored in memory, like any other variable.
• Such variables that hold memory addresses are
called pointer variables.
• A pointer variable is, nothing but a variable that
contains an address, which is a location of another
variable in memory.
ACCESSING THE ADDRESS OF A
VARIABLE
• The actual location of a variable in the memory is
system dependent.
• We can determine the address of a variable with the
help of the operator & available in C.
• The operator & immediately preceding a variable
returns the address of the variable associated with it.
p = &quantity
• Would assign the address 5000 to the variable p
CHAIN OF POINTERS
• It is possible to make a pointer to point to another pointer,
thus creating a chain of pointers.

• The pointer variable p2 contains the address of the pointer


variable p1, which points to the location that contains the
desired value. This is known as multiple indirections.
• A variable that is a pointer to a pointer must be declared
using additional indirection operator symbols in front of the
name.
• This declaration tells the compiler that p2 is a pointer to a
pointer of int type.
CHAIN OF POINTERS
• We can access the target value indirectly pointed to by
pointer to a pointer by applying the indirection operator
twice.
main()
{
int x, *p1, **p2;
x = 100;
p1 = &x; /* address of x */
p2 = &p1; /* address of p1 */
printf("%d", **p2);
}
POINTER EXPRESSION
• Like other variables, pointer variables can be used in
expressions.
• If p1 and p2 are properly declared and initialized pointers, the
following statements are valid:
y = *p1 * *p2 same as (*p1) * (*p2)
sum = sum + *p1;
z = 5* - *p2/ *p1; same as (5 * (-(*p2)))/(*p1)
*p2 = *p2 +10;
• Note the blank space between / and *. the following is wrong
z = 5* - *p2 /*p1;
• The symbol /* is considered as the beginning of a comment
POINTER EXPRESSION
• C allows us to add integers to or subtract integers from pointers,
as well as to subtract one pointer from another.
p1 + 4, p2 – 2, p1 - p2 are all allowed
• If p1 and p2 are both pointer to the same array, then p2-p1 gives
the number of elements between p1 and p2.
• We may also use short-hand operators with the pointers.
p1++; -p2; sum += *p2;
• Pointer can also be compared using the relational operators.
p1 > p2, p1 == p2, p1 != p2 are allowed
• We may not use pointers in division or multiplication.
p1/p2 or p1 * p2 or p1 / 3 are not allowed
• Two pointer cannot be added.
p1 + p2 is illegal
EXAMPLE
main() printf("a = %d, b = %d\n", a, b);
{ printf("x = %d, y = %d\n", x, y);
int a, b, *p1, *p2, x, y, z; *p2 = *p2 + 3;
a = 12; *p1 = *p2 - 5;
b = 4; z = *p1 * *p2 - 6;
p1 = &a; printf("\na = %d, b = %d,", a, b);
p2 = &b; printf(" z = %d\n",z);
x = *p1 * *p2 -6; }
y = 4* - *p2 / *p1 + 10; OUTPUT:
printf("Address of a = %d\n", p1); Address of a = 4020
printf("Address of a = %d\n", p2); Address of b = 4016
printf("\n"); a = 12, b = 4
x = 42, y = 9
a = 2, b = 7, z = 8
Pointer Increments and Scale Factor
• Arithmetic operations can be performed on pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
• The pointers can be incremented like
p1 = p1 + 2;
p1 = p1 + 1;
• Expression like
p1++;
• Will cause the pointer p1 to point to the next value of its type
• When a pointer is incremented, its value is increased by the
‘length’ of the data type that it points to
• This length called the scale factor
Pointers and Arrays
• When an array is declared, the compiler allocates a base address
and sufficient amount of storage to contain all the elements of
the array in contiguous memory locations
• The base address is the location of the first elements (index 0) of
the array
• The compiler also defines the array name as the constant pointer
to the first element
int x[5] = {1, 2, 3, 4, 5};
• Base address of x is 1000
• Each integer requires two bytes
• The name x is defined as a constant pointer pointing to the first
element, x[0]
• The value of x is 1000, the location where x[0] is stored
x = &x[0] = 1000
• Declare p as an integer pointer, then we can make the pointer p
to point to the array x
p = x;
Pointers and Arrays
• This is equivalent to
p = &x[0];
• We can access every value of x using p++ to move from one
element to another
• The relationship between p and x is
p = &x[0] (=1000)
p+1 = &x[1] (=1002)
p+2 = &x[2] (=1004)
p+3 = &x[3] (=1006)
P+4 = &x[4] (=1008)
• The address of an element is calculated using its index and the
scale factor of the data type
Address of x[3] = base address + (3 x scale factor of int)
= 1000 + (3 x 2) = 1006
• When handling arrays, instead of using array indexing, we can
use pointers to access array elements.
• The pointer accessing method is much faster than array
indexing.
EXAMPLE
main() OUTPUT:
{ Element Value Address
int *p, sum, i; x[0] 5 166
int x[5] = {5,9,6,2,7}; x[1] 9 168
i = 0; p = x; x[2] 6 170
printf("Element Value Address\n\n"); x[3] 3 172
while(i<5) x[4] 7 174
{ Sum = 55
printf(" x[%d] %d %d\n",i, *p, p); &x[0] = 166
sum = sum + *p; p = 176
i++; p++;
}
printf("\n Sum = %d\n", sum);
printf("\n &x[0] = %d\n", &x[0]);
printf("\n p = %d\n", p);
}
POINTERS TO 2D ARRAYS
• Pointers can be used to manipulate two-dimensional arrays as
well.
• In a one-dimensional array x, the expression
*(x+i) or *(p+i)
• Represents the elements x[i].
• An element in a two-dimensional array can be represented by
the pointer expression as:
*(*(a+i)+j) or *(*(p+i)+j)
POINTERS AND CHARACTER STRINGS
• The strings are treated as character arrays and therefore they are
declared and initialized as
char str[5] = “good”;
• The compiler automatically inserts the null character ‘\0’ at the
end of the string.
• Alternate method to create stings is by using pointer variables of
type char.
char *str = “good”;
• This creates a string and then stores its address in the pointer
variable str.
• The pointer str now points to the first character of the string
“good” as:
POINTERS AND CHARACTER STRINGS
• We can use the run-time assignment for giving values to a
string pointer.
char * string1;
string1 = “good”;
• The above assignment is not a string copy, because the
variable string1 is a pointer, not a string.
• We can print the content of the string string1 using either
printf or puts functions as
printf(“%s”, string1);
puts(string1);
• Although string1 is a pointer to the string, it is also the name of
the string. Therefore we do not need to use the indirection
operator * here
EXAMPLE
main()
OUTPUT:
{
DELHI
char *name;
D is stored at address 54
int length;
E is stored at address 55
char *cptr = name;
L is stored at address 56
name = DELHI;
H is stored at address 57
printf("%s\n“,name);
I is stored at address 58
while(*cptr != '\0')
{
Length of the string = 5
pritf("%c is stored at address %d\n", *cptr, cptr);
cptr++;
}
length = cptr - name;
printf("\nLength of the string = %d\n", length);
}
POINTER AS FUNCTION ARGUMENTS
• When an array is passed to a function as an argument, only the
address of the first element of the array is passed, but no the
actual values of the array elements.
• If x is an array, when we call sort(x), the address of x[0] is passed
to the function sort.
• The function used this address for manipulating the array
elements.
• We can also pass the address of a variable as an argument to a
function.
• When we pass addresses to function, the parameters receiving
the addresses should be pointers.
• The process of calling a function using pointers to pass the
addresses of variables is known as ‘call by reference’.
• The function called by ‘reference’ can change the value of the
variable used in the call.
EXAMPLE
main()
{
int x;
x = 20;
change(&x);
printf("%d\n",x);
}
change(int *P)
{
*P = *P + 10;
}
OUTPUT:
30
Pointers with Functions (example)
void swap ( int *, int * ) ; Results:
main ( ) Before Swapping : a=5 b=6
{ After Swapping : a=6 b=5
int a = 5, b = 6;
printf(“Before Swapping : a=%d b=%d\n",a,b) ;
swap (&a, &b) ;
printf(“After swapping : a=%d b=%d\n",a,b) ;
}
void swap( int *a, int *b )
{
int temp;
temp= *a; *a= *b; *b = temp ;
}
FUNTION RETURNING POINTERS
• Function can also return a pointer to the calling function
int *larger (int *, int *);
main() {
int a = 10, b = 20;
int *p;
p = larger(&a, &b);
printf("%d", *p);
}
int *larger(int *x, int *y)
{
if(*x>*y)
return(x);
else
return(y);
}
THE END

You might also like