Вы находитесь на странице: 1из 10

MODULE 5

Pointers
A pointer is a derived data type. It is built in from one of the fundamental data type
available in c. Pointers contains memory addresses as their values. Pointers are used for the
following benefits to the programmers.
They are
Pointers are more efficient in handling arrays and data tables.
Pointers can be used to return multiple values from a function via function arguments.
Pointer reduces length and complexity of program.
They increase the execution speed.
Pointers allow C to support dynamic memory management.
It is widely used in data structure.
The use of pointer arrays to character strings results in saving of data storage space in
memory.
Accessing the address of a variable:The operator & is used to access the address of the variable associated with it.
E.g., p=&quantity;
Declaring pointer variable:The declaration of the pointer variables takes the following form: data_types *var-name;
example:- int*p;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Some of the valid pointer declarations are
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The
only difference between pointers of different data types is the data type of the variable or
constant that the pointer points to.
Initialization of pointer variable:A process of assigning the address of a variable to the pointer variable is known as
initialization.
Example:int quantity;
Int *p;
P=&quantity;
Initialization of Pointer can be done using following 4 Steps
1. Declare a Pointer Variable and Note down the Data Type.

2. Declare another Variable with Same Data Type as that of Pointer Variable.
3. Initialize Ordinary Variable and assign some value to it.
4. Now Initialize pointer by assigning the address of ordinary variable to
pointer variable.
E.g.,
#include<stdio.h>
int main()
{
int a;

// Step 1

int *ptr; // Step 2


a = 10;
ptr = &a;

// Step 3
// Step 4

return(0);
}

Accessing a variable through its pointer:int quantity, *p, n;


quantity=175;
P=&quantity;
n=*p;
PROGRAM TO FIND REVERSE OF A NUMBER
#include<stdio.h>
#include<conio.h>
void main()
{
int n,a;
int *rev,*rem,*temp;
clrscr();
printf(Enter any number: );
scanf(%d,&n);
a=n;
temp=&n;
*rev=0;
while(*temp>0)

{
*rem=*temp%10;
*temp=*temp/10;
*rev=(*rev)*10+*rem;
}
printf(Reverse of %d is %d,a,*rev);
getch();
}
Chain of Pointers
A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer to a pointer,
the first pointer contains the address of the second pointer, which points to the location that
contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by


placing an additional asterisk in front of its name. For example, the following declaration
declares a pointer to a pointer of type int
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that
value requires that the asterisk operator be applied twice, as is shown below in the example
#include <stdio.h>
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
When the above code is compiled and executed, it produces the following result
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Pointer expression and pointer airthmetic
Like other variables pointer variables can be used in expressions. For example if p1
and p2 are properly declared and initialized pointers, then the following statements are valid.

y=*p1**p2;
sum=sum+*p1;
z= 5* - *p2/p1; same as (5*(-(*p2)))/ (p1)
*p2= *p2 + 10;
C allows us to add integers to or subtract integers from pointers as well as to subtract
one pointer from the other. We can also use short hand operators with the pointers p1+=;
sum+=*p2; etc.
we can also compare pointers by using relational operators the expressions such as p1
>p2 , p1==p2 and p1!=p2 are allowed.
/*Program to illustrate the pointer expression and pointer arithmetic*/
#include< stdio.h >
#include< stdio.h >
main()
{
int a, b, *p1, *p2, x, y, z;
a = 12;
b = 4;
p1 = &a;
p2 = &b;
x = *p1 * *p2 - 6;
y = 4* - *p2 / *p1 + 10;
printf("Address of a = %u\n", p1);
printf("Address of b = %u\n", p2);
printf("\n");
printf("a = %d, b = %d\n", a, b);
printf("x = %d, y = %d\n", x, y);
*p2 = *p2 + 3;
*p1 = *p2 - 5;
z
= *p1 * *p2 - 6;
printf("\na = %d, b = %d,", a, b);
printf(" z = %d\n", z);
}
Output
Address of a = 4020
Address of b = 4016
a = 12, b = 4
x = 42, y = 9
a = 2, b = 7, z = 8

Pointer Increments And Scale Factor


The pointers can be increments like
p1 = p2 + 2;
p1 = p1 + 1;and so on. However, an expression like p1++; well cause the pointer p1 to pointer
to the next value of its type. For example, if p1 is an integer pointer with an initial value, say
2800, then after the operation p1= p1 + 1, the value of p1 will be2802, and not 2801. that is,
when increment a pointer, its value is increased by the 'length' of the data type that it
points to. This length called the scale factor.
for an IBM PC, the length of various data types are as follows:
characters

1 byte

Integers

2 bytes

Floats

4 bytes

long integers

4 bytes

Doubles
8 bytes
The number of bytes used to store various data types depends on the system and can
be found by making use of the sizeof operator. For example, if x is a variable, then sizeof(x)
returns the number of bytes needed for the variable.
1)for example a series of three variables of short type are declared and a pointer is stored with
the
address
of
a
variable

short a=10,b=20,c=30;
short *p=&c;
Here p is the pointer to the variable c, holds the address of c 65520. Now p+1 gives the
address of next variable b 65522 and p+2 gives the address of next variable a 65524.
#include<stdio.h>
int main()
{
short a=10,b=20,c=30;
short *p=&c;
printf("\np %u",p);
printf("\np+1 %u",p+1);
printf("\np+2 %u",p+2);
return 0;
}
Output:
p
65520
p+1
65522
p+2 65524
By this the value of short pointer increments by 2 on adding 1 to the pointer.
2)If we take a float pointer then increments by 4 on adding 1 to the pointer.
#include<stdio.h>
int main()
{
float a=10.34,b=20.56,c=30.44;
float *p=&c;
printf("p %u",p);
printf("\np+1 %u",p+1);
printf("\np+2 %u",p+2);
return 0;
}
Output:
p
p+1
p+2 65522
Rules for using Pointer :
1.
Pointer Variable Can be Assigned the address of another Variable

65514
65518

int main()
{
int num = 10;
int *ptr;
ptr = &num;
return(0);
}
2.
Pointer Variable Can be Assigned the value of another Pointer Variable
int *sptr,*tptr;
sptr = &num;
tptr = sptr;
3.

4.

5.

6.
7.
8.
9.

Pointer Variable Can be initialized with zero or NULL value.


int *sptr,*tptr;
sptr = 0;
tptr = NULL;
Pointer variable Can be Perform Pre/Post fix Increment/Decrement Operation
int arr[20];
int *ptr;
ptr = &arr;
ptr++;
Integer value can be added or Subtracted from Pointer variable
int arr[20];
int *ptr;
ptr = &arr;
ptr = ptr + 2; //arr[2] will be accessed
When two Pointer points to same array then one Pointer variable can be Subtracted from
another
Two Pointers pointing to objects of same data type then they can be compared using the
Relational Operator
Value cannot be assigned to arbitrary address
int *ptr;
ptr = 100; //Illegal
Pointer Variable cannot be multiplied by Constant
int *ptr;
ptr = ptr * 6; //Illegal

Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to contain
all the elements of the array. Base address which gives location of the first element is also
allocated by the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
element will be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to
another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use that
pointer to access the array. Lets have an example,
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++;
}
In the above program, the pointer *p will print all the values stored in the array one by one.
We can also use the Base address (a in above case) to act as pointer and print all the values.

Pointer to Multidimensional Array


A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to
such an array. As we know now, name of the array gives its base address. In a[i][j], a will
give the base address of this array, even a+0+0 will also give the base address, that is the
address of a[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(ptr + i) + j)
is same as
a[i][j]

Pointer and Character strings


Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The
pointer str now points to the first character of the string "Hello". Another important thing to
note that string created using char pointer can be assigned a value at runtime.
char *str;

str = "hello"; //thi is Legal


The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need
to use indirection operator *.
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 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.

Вам также может понравиться