Unit-1 Introduction to Pointer
Unit-1 Introduction to Pointer
What is Pointer?
int X = 547;
HERE
:
Variable name Content Location
s
X 547 4000
According to above figure, by the help of ptr variable we stored the address of variable X in
address 4036
Advantage of Pointer:-
1) Pointer can be used to return multiple values from function via arguments or parameters.
2) Pointer is easy to for handling array.
3) Pointer permits references to function and thereby facilitating passing of function as
arguments to other function.
4) Pointers array using to character string results in saving of data storage space in memory.
5) Pointers reduce length & complexity of program.
6) Pointers increase the execution speed & thus reduce the program execution time.
7) More compact and efficient coding
8) It support Dynamic memory Allocation
9) C uses pointers explicitly with: Array, Function & Structures.
BMU-BMCCA Page 1 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Disadvantage of pointer:-
If sufficient memory is not available during runtime for the storage of pointers, the program
may crash (least possible)
“Address Operator” which gives or produces the memory address of data variable
The actual location of a variable is system depended and the address is not known to us
immediately. This can be done with the help of & (address operator) available in C.
The operator & preceding a variable returns the address of a variable associated with it.
P = &i;
This would assign the address 5000 to the variable P. when preceding the name of the
variable i with the reference operator (&) we are no longer talking about the content of the
variable p but about its reference (i.e. address in the memory)
We declare a pointer variable we must point it to something we can do this by assigning to
the pointer the address of the variable you want to point as in the following example:
ptr = #
This places the address where num is stores into the variable ptr. If num is stored in
memory 2101 address then the variable ptr has the value 2101
Pointer variables are declared just like any other variable. When pointer variable is
declared, the variable name must be preceded by an asterisk (*). This identifies that the
variable is a pointer.
In ‘c’ Every Variable must be Declared its type ,since pointer variables contain address of
separate Data type , They must be Declared before use them the declaration of pointer
variable takes the following form
Syntax:
Variable name is the name of the pointer variable, and data type refers to the data type of
the pointer’s object.
Here are three things about the pointer variable:
The asterisk (*) sign tells the variable pt_name is a pointer variable.
Ptr_name needs a memory location.
Ptr_name points to a variable of type data_type.
Example:
1. Int * p ; / * integer pointer */
2. float *ptr; /* float pointer */
HERE:
1. Declares the variable ‘p’ as a pointer variable that points to an integer data type
2. Declares the variable ‘ptr’ as a pointer variable that points to an ‘float’ data type
There are three different ways to declare the pointer
BMU-BMCCA Page 2 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
2. This style matches with the format used for accessing the target values.
Example:
int x, *p , y;
x=10;
y=*p;
*p = 20;
e.g.: int *numPtr; // Declare the int* (pointer to int) variable "numPtr".
// this allocates space for the pointer.
OUTPUT:
Address of var = 4056
The content of var = 486
As ordinary variables are Initialized with in Declaration part of the program ,The Pointer
variables can initialized by Accessing address of the variable that are Used in the program .
The initializer is a = (equal sign) followed by the expression that represents the address
that the pointer is to contain.
Syntax:
Data_type *ptr = expression
Where:
data_type = Any Basic Data type
*ptr = pointer variable
expression = another variable or may be constant
Example:
int quantity;
int *p ; /* Declaration */
p = &quantity; /* initialization*/
Here, the third line assigns the address of ‘quantity’ to pointer variable ‘p’
BMU-BMCCA Page 3 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Initialization for array: The compiler converts an unsubscripted array name to a pointer
to the first element in the array. You can assign the address of the first element of an array
to a pointer by specifying the name of the array.
For example:
int array[20];
int *a=array;
is equivalent to:
int array[20];
int *a=&a[0];
Initialization for String: You can assign the address of the first character in the string
constant to a pointer by specifying the string constant in the initializer.
For example
char *str=”abc”;
The following example defines the fruits as a array of pointers to string constants. Each
element points to different string. The pointer fruits[1],for example , point to a string
“orange”.
char *fruits[]={“banana”,”orange”,”apple”,”mango” }
A pointer can also be initialized to null using any integer constant expression that evaluates
to 0, for example char *a=0;. Such a pointer is a null pointer. It does not point to any
object.
Invalid initializations:-
1. float a,b;
int x,* p;
p = &a; /* wrong */
b = *p;
Here, we will get erroneous output because we are trying to assign the address of float
variable to an integer variable it is not allowed in pointer assignments.
Here, it declares ‘x’ as integer variable, ‘p’ as pointer variable then assign
‘p’ to the address of ‘x’. First we must be declare the ‘x’ before initialization hence above
statement gives the erroneous output
0UTPUT:
The content of the variable ‘m’ = 270
The content of the variable ’m’ after initialization = 412
BMU-BMCCA Page 4 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
#include <stdio.h>
Void main( ) 100 102
{ 102 3
int a=3,b; ptr a
int *ptr,*ptr1; // Pointer to an integer
ptr=&a; //assign address of a to ptr 200 202
b=*ptr; //assign the value of a
102 3
ptr1=&b; //assign the address of b to ptr1
ptr1=ptr; // assign the value of ptr to ptr1 b
ptr1
printf(“\n a=%d &a=%d *ptr=%d”,a,&a,*ptr);
printf(“\n b=%d &b=%d *ptr1=%d ptr1=%d”,b,&b,*ptr1,ptr1);
getch();
}
#include <stdio.h>
#include <conio.h>
int main()
{
double radius=2.0,area;
double *pradius, *parea;
pradius=&radius;
parea=&area;
*parea= 3.14 * (*pradius) * (*pradius);
printf("%f", *parea);
getch();
}
NULL Pointer:-
The constant NULL is a special pointer value which encodes the idea of "points to nothing."
num
The C language uses the symbol NULL for this purpose. NULL is equal to the integer
Constant 0, so NULL can play the role of a Boolean false.
1. A pointer variable can be assigned the address of an ordinary variable. (E.g. ptr=&a)
2. A pointer variable can be assigned the value of another variable (e.g. ptr=ptr1) provide
both pointers point to objects of the same data type.
3. A pointer variable can be assigned a null value. (E.g. ptr=NULL, where it represents the
value 0)
4. An integer quantity can be added to or subtracted from a pointer variable. (E.g. ptr++,
ptr+2 etc.)
5. One pointer variable can be subtracted from another provided both pointers point to
elements of the same array.
6. Two pointer variables can be subtracted from another provided both pointers point to
objects of the same type.
Other arithmetic operations on pointers are not allowed. Thus, Pointer variable can not be
multiplied by a constant; two pointer variables can not be added; and so on.
BMU-BMCCA Page 5 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Example: Two different pointer variables point to the first & last elements of an integer array.
#include<stdio.h> Memory
Location
main()
{ 1 2
int *ptr,*ptr1;
int a[6]={1,2,3,4,5,6}; 2 4
ptr=&a[0];
3 6 12-2=10
ptr1=&a[5];
printf(“\n The value of 2 pointers are :%d”, ptr,ptr1); 10/2=5
4 8
printf(“\n subtraction is (ptr1-ptr)=%d”, ptr1-ptr);
getch(); 5 10
} Size of data type
6 12
Output:-
The value of 2 pointers are:ptr=2 ptr1=12 Write This Statement instead of ptr1-ptr
Subtraction is (ptr1-ptr) =5
Here we can write statement like ptr1+ptr than it generate the error Illegal pointer addition.
Address Value
[Single Indirection]
The value of normal pointer is the address of object that contains the desire value.
[Pointer to Pointer]
In pointer to pointer, the first pointer contains the address of the second pointer, which
points to the object that contains the desired value.
The declaration of pointer to pointer is, (use additional asterisk in front of the variable
name)
Syntax:
Data_type **ptr
Example:
#include <stdio.h>
int main(void)
{
int x,*p,**q;
x=10;
p=&x;
q=&p;
printf(“%d\n”, **q);
getch()
}
BMU-BMCCA Page 6 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Pointers can be used to pass addresses of variables to called functions, thus allowing the
called function to alter the values stored there.
We looked earlier at a swap function that did not change the values stored in the main
program because only the values were passed to the function swap.
This is known as "call by value".
If instead of passing the values of the variables to the called function, we pass their
addresses, so that the called function can change the values stored in the calling
routine.This is known as "call by reference" since we are referencing the variables.
The following shows the swap function modified from a "call by value" to a "call by
reference". Note that the values are now actually swapped when the control is returned to
1main function.
Pointers with Functions (Examples)
Example1:
BMU-BMCCA Page 7 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Example2:
#include<stdio.h>
#include<conio.h>
void calc(int x, int y, int *add, int *sub)
{
*add = x+y;
*sub = x-y;
}
void main()
{
int a=20, b=11, p,q;
clrscr();
calc(a,b,&p,&q);
printf("Sum = %d, Sub = %d",p,q);
getch();
}
Array name is pointer to the first element in the array. Therefore, if a is a one
dimensional array, then the address of the first array element can be expressed as either
&a[0] or simply as a. the address of second array element can be written as either &a[1]
or as (a+1) and so on. In general, the address of array element (i+1) can be expressed
as either &a[i] or as (a+i).
We have two different ways to write the address of any array element:
We can write the actual element preceded by ampersand. e.g. &a[i]
We can write an expression in which the subscript is added to the array name like (a+i)
If numerical array is defined as pointer variable, the array elements can not be assigned
inital values.
A character type pointer variable can be assigned an entire string as a part of the variable
declaration. Thus, a string can be represented by either a one dimensional character
array or a character pointer.
#include<stdio.h>
void main()
{
inti,n, *pa;
printf("Input the value of N\n");
scanf("%d", &n);
pa=(int*)malloc(n*sizeof(int)) ;
printf("Input %d values\n", pa);
for(i=0;i<n;i++)
{
scanf("%d", (pa+i));
}
printf("\n print array using dynamic pointer\n");
for(i=0;i<n;i++)
{
printf(“%d -- %d\n",(pa+i),*(pa+i));
}
}
BMU-BMCCA Page 8 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Multidimensional Array:-
rather than
Example: write a program to input the elements of 2 matrix and display in table form.
#include<stdio.h>
void input(int *a[3],int row,int col);
void display(int *a[3],int row,int col);
void main()
{
int *a[3],*b[3],r,c,row;
printf(“Enter the No Of Rows:”);
scanf(“%d”,&r);
printf(“Enter the no of column:”);
scanf(“%d”,&c);
//allocate the initial memory
for(row=0;row<r;row++)
{
a[row]=(int *)malloc(c*sizeof(int));
b[row]=(int *)malloc(c*sizeof(int));
}
//First matrix
input(a,r,c);
display(a,r,c);
//Second marix
input(b,r,c);
display(b,r,c);
getch();
}
void input(int *a[3],int i,int j)
{
int r,c;
for(r=0;r<i;r++)
{
for(c=0;c<j;c++)
{
sacnf(“%d”,(*(a+r)+c));
}
}
BMU-BMCCA Page 9 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Array of Pointer:-
Syntex:
Data type *array[expression 1]
The array name and its preceding asterisk are not enclosed in parentheses in this type of
declaration. Thus, a right to left rule first associates the pairs of square brackets with array,
defining the named object as an array. The preceding asterisk then establishes that the
array will contain pointers.
Suppose a is a two dimensional array having 3 rows and 3 columns, as we define a as a one
dimensional array of pointers by writing
int *a[3];
rather than
int a[3][3];
a[0] points to the beginning of the first row, a[1] points to the beginning of the second row.
An individual array element, such as a[2][5],can be accessed by writing
*(a[2]+5)
#include<stdio.h>
void input(int *a[3],int row,int col);
void display(int *a[3],int row,int col);
void add(int *a[3],int *b[3],int *sum[3],int row,int col);
main()
{
int *a[3],*b[3],*sum[3],r,c,row;
printf(“Enter the No Of Rows:”);
BMU-BMCCA Page 10 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
scanf(“%d”,&r);
printf(“Enter the no of column:”);
scanf(“%d”,&c);
//allocate the initial memory
for(row=0;row<r;row++)
{
a[row]=(int *)malloc(c*sizeof(int));
b[row]=(int *)malloc(c*sizeof(int));
sum[row]= (int *)malloc(c*sizeof(int));
}
//First matrix
input(a,r,c);
display(a,r,c);
//Second matrix
input(b,r,c);
display(b,r,c);
//sum of two matrix
add(a,b,sum,r,c);
display(sum,r,c);
getch();
}
void input(int *a[3],int i,int j)
{
int r,c;
for(r=0;r<i;r++)
{
for(c=0;c<j;c++)
{
sacnf(“%d”,(a[r]+c));
}
}
}
void display(int *a[3],int i,int j)
{
int r,c;
for(r=0;r<i;r++)
{
for(c=0;c<j;c++)
{
printf(“%d”,*(a[r]+c));
}
}
}
void add(int *a[3],int *b[3], int *sum[3],int i,int j)
{
int r,c;
for(r=0;r<i;r++)
{
for(c=0;c<j;c++)
{
*(sum[r]+c)=*(a[r]+c) + *(b[r]+c);
}
}
}
BMU-BMCCA Page 11 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
Pointer to Array:-
If we can have a pointer to an integer, a pointer to a float, a pointer to a char, then can we
not have a pointer to an array? We certainly can. The following program shows how to build
& use it.
C allows pointer to structures. There are two primary uses for structure pointers:
When a pointer to structure is passed to a function, only the address of the structure is
pushed on the stack. This makes for very fast function calls.
Second advantage is that passing pointer makes it possible for the function to modify the
contents of the structure used as the argument.
Structure pointers are declared by placing * in front of structure variable’s name.
Where data type is identifies the composition of the structure, and ptr represents the name
of the pointer variable. We can then assign the beginning address of a structure variable to
this pointer by writing
ptr_variable=&structure_variable;
struct employee
{
int ano;
char name[30];
}emp;
OR
struct employee
BMU-BMCCA Page 12 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
{
int ano;
char name[30];
};
struct employee emp, *e; // declare a structure pointer
This places the address of the structure emp into the pointer e;
e=&emp;
To access the members of a structure using a pointer to that structure, you must ( )
use the Operator
e.g.: e ano
The -> operator can be combined with the period operator to access a submember within a
structure. A submember can be accessed by writing
ptr_variable member_name.submember_name
BMU-BMCCA Page 13 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
scanf(“%d”,&s->no);
printf(“Name”);
scanf(“%s”,s->name);
printf(“Per”);
scanf(“%f”,&s->per);
}
Void display(struct student *s)
{
printf(“roll no=%d”,&s->no);
Printf(“Name=%s”,s->name);
printf(“Per=%f”,s->per);
}
Question Bank
Short Question (Marks-2)
BMU-BMCCA Page 14 of 15
1020406104-Data Structures UNIT-1:Pointer By :Sneha Patel
BMU-BMCCA Page 15 of 15