Faculty: Ch.
Lavanya Susanna, dept of cse
Unit-4
Pointers:
In the c programming language, every variable has a name, datatype, value, storage class, and address. A
pointer is defined as follows...
Pointer is a special type of variable used to store the memory location address of a variable.
Declaring a pointer variable:
Syntax:
Datatype *pointer;
Every pointer variable is preceded by „*‟ symbol.
Every pointer stores the address the variable with same datatype only. That means integer pointer is used
store the address of integer variable only.
Example:
int *p;
Here p is a pointer variable which stores address of an integer variable;
float *p1;
Here p1 is a pointer variable which stores address of a float variable;
double *p2;
Here p2 is a pointer variable which stores address of a double variable;
char *p3;
Here p3 is a pointer variable which stores address of a character variable;
Accessing the Address of Variables:
A Reference operator "&" is used to access the address of variable. After declaring pointer, the address of
a variable of same type must be assigned to it.
Example:
int a=10; p a
int *p;
1000 10
p = &a;
1000
Here the pointer p contains address of an integer variable „a‟. That means the pointer is pointing to variable „a‟.
float b=2.5; p1 b
float *p1;
1004 2.5
p1 = &b;
1004
Here the pointer p1 contains address of a float variable „b‟. That means the pointer is pointing to variable „b‟.
double c=2.5345 p2 c
double *p2;
1008 2.5345
p2 = &c;
1008
Here the pointer p2 contains address of a double variable „c‟. That means the pointer is pointing to variable „c‟.
char ch=‟A‟; p3 ch
char *p3;
1017 A
p3 = &ch;
1017
Here the pointer p3 contains address of a character variable „ch‟. That means the pointer is pointing to variable „ch‟.
1
Faculty: Ch.Lavanya Susanna, dept of cse
Accessing variable value using pointers:
Pointer variables are used to store the address of other variables , this address can be used to access the value of the
variable through its pointer. Symbol “*” in front of pointer variable name is used to access the value of variable to
which the pointer is pointing.
Example:
int a=10; p a
int *p;
1000 10
p = &a;
1000
To access the value of variable a using pointer
*p – this gives the value of variable a
p – this gives address of variable a
to modify the value of variable „a‟ using pointer
*p=20
Now the value of variable „a‟ is modified to 20
p a
1000 20
1000
C program to demonstrate the use of & (address of) , * (value at address) Operator
#include <stdio.h>
void main()
{
int a = 10;
int * p;
p = &a;
printf("Address of a= %u\n", &a);
printf("Value of a= %d\n", a);
printf("content of pointer = %u\n", p);
printf("Value pointed by pointer = %d\n", *p);
}
Output:
Address of num = 28322996
Value of num = 10
content of pointer = 28322996
Value pointed by pointer = 10
C program in c two add two numbers using pointers
#include <stdio.h>
void main()
{
int a, b, sum;
int *p, *q;
printf("Enter two integers to add\n");
scanf("%d%d", &a, &b);
p = &a;
q = &b;
sum = *p + *q;
printf("Sum of the numbers = %d\n", sum);
}
2
Faculty: Ch.Lavanya Susanna, dept of cse
Output:
Enter two integers to add
34 45
Sum of the numbers = 79
void pointer or generic pointer:
A void pointer is a special pointer that can point to object of any type.
(or)
A void pointer is a pointer variable used to store the address of a variable of any datatype. That means single
void pointer can be used to store the address of integer variable, float variable, character variable, double variable or
any structure variable
Syntax to declare a void pointer
void *pointer-name;
Here keyword "void" is used to create void pointer
now assigning new address
p=&b;
here pointer p points to float variable
To access the values by generic pointer (dereferencing):
Consider the above example
To refer any datatype value by generic pointer
Syntax:
*( (datatype*) pointer )
Here pointer must point to the specified datatype
Example: To refer integer value by generic pointer p
*( (int*) p)
This gives value stored in integer variable which is pointed by p i.e 10
3
Faculty: Ch.Lavanya Susanna, dept of cse
C program to demonstrate generic pointer or void pointer
#include<stdio.h>
void main()
{
int a=10 ;
float b=2.5 ;
char c='A' ;
void *ptr ;
ptr=&a ;
printf("value of integer variable is %d\n", *((int*)ptr)) ;
ptr=&b ;
printf("value of float variable is %f\n", *((float*)ptr)) ;
ptr=&c ;
printf("value of character variable %c\n", *((char*)ptr)) ;
}
Output:
value of integer variable is 10
value of float variable is 2.500000
value of character variable A
Pointer to pointer:
A pointer which stores the address of another pointer of same type, such pointer is known as a
double pointer (pointer to pointer).
Syntax for declaring double pointer:
datatype **pointer;
Example:
int a=10; a p pp
int *p; 10 1002 1004
int **pp; 1002 1004 1008
p=&a;
pp=&p;
Now changing the value of variable „a‟ using single pointer
*p=20;
The value of variable „a‟ is changed to 20
Now changing the value of variable „a‟ using double pointer
**pp=30;
The value of variable „a‟ is changed to 30
4
Faculty: Ch.Lavanya Susanna, dept of cse
C program to demonstrate double pointer or pointer to pointer:
#include<stdio.h>
#include<conio.h>
void main()
{
int a ;
int *p ;
int **pp ;
p = &a ;
pp = &p ;
printf("Address of normal variable is %u\n", p) ;
printf("Address of pointer variable is %u\n", pp) ;
}
Output:
Address of normal variable is 2346607612
Address of pointer variable is 2346607616
Pointers Arithmetic Operations in C: A pointer in c is an address, which is a numeric value. Therefore, arithmetic
operations on a pointer can be performed just as done on a numeric value. In the c programming language, we can
perform the following arithmetic operations on pointers...
1. Addition
2. Subtraction
3. Increment
4. Decrement
5. Comparison
1. Addition Operation on Pointer: A value to the pointer variable can be added using following formula
new_address= current_address + (value_to_be_added * size_of(data type))
Example: x p
int x=20;
20 1000
int *p;
p=&x; 1000
Performing addition operation on pointer p
p=p+3
Using formula the new address of p is
current_address + (value_to_be_added * size_of(data type))
=1000 + ( 3 * size of ( int ) )
=1000 + (3 * 2) p
=1000+6
=1006 1006
5
Faculty: Ch.Lavanya Susanna, dept of cse
C program to perform Addition Operation on Pointer
#include<stdio.h>
void main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u \n",p);
p=p+3;
printf("After adding 3: Address of p variable is %u \n",p);
}
Output:
Address of p variable is 2580384180
After adding 3: Address of p variable is 2580384192
Here above output is executed in 32 bit so size of int is 4 bytes
2. Subtraction Operation on Pointer: A value to the pointer variable can be added using following formula
new_address= current_address - (value_to_be_added * size_of(data type))
Example: x p
int x=20;
20 1000
int *p;
p=&x; 1000
Performing Subtraction operation on pointer p
p=p-3
Using formula the new address of p is
current_address - (value_to_be_added * size_of(data type))
=1000 - ( 3 * size of ( int ) )
=1000 - (3 * 2) p
=1000 - 6
=994 994
C program to perform Addition Operation on Pointer
#include<stdio.h>
void main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u \n",p);
p=p-3;
printf("After adding 3: Address of p variable is %u \n",p);
}
Output:
Address of p variable is 2502375604
After adding 3: Address of p variable is 2502375592
Here above output is executed in 32 bit so size of int is 4 bytes
3. Incrementing pointer: Incrementing pointer by 1, the pointer will start pointing to the immediate next location.
This is somewhat different from the general arithmetic since the value of the pointer will get increased by the size of
the data type to which the pointer is pointing.
The formula is
new_address= current_address + size_of(data type)
6
Faculty: Ch.Lavanya Susanna, dept of cse
Example: x p
int x=20;
20 1000
int *p;
p=&x; 1000
Performing increment operation on pointer p
p++; //similar to p=p+1;
Using formula the new address of p is
current_address + size_of(data type)
=1000 + size of ( int )
=1000 + 2 p
=1000+2
=1002 1002
C program to perform increment Operation on Pointer
#include<stdio.h>
void main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u \n",p);
p++;
printf("After adding 3: Address of p variable is %u \n",p);
}
Output:
Address of p variable is 2443027172
After adding 3: Address of p variable is 2443027176
4. Decrementing pointer: decrementing pointer by 1, the pointer will start pointing to the previous location. This is
somewhat different from the general arithmetic since the value of the pointer will get decreased by the size of the
data type to which the pointer is pointing.
The formula is
new_address= current_address - size_of(data type)
Example: x p
int x=20;
20 1000
int *p;
p=&x; 1000
Performing decrement operation on pointer p
p--; //similar to p=p-1;
Using formula the new address of p is
current_address - size_of(data type)
=1000 - size of ( int )
=1000 - 2 p
=1000-2
=998 998
C program to perform decrement Operation on Pointer
#include<stdio.h>
void main()
{
int number=50;
int *p;
p=&number;
printf("Address of p variable is %u \n",p);
p--;
printf("After adding 3: Address of p variable is %u \n",p);
}
Output:
Address of p variable is 4002556212
7
Faculty: Ch.Lavanya Susanna, dept of cse
After adding 3: Address of p variable is 4002556208
Pointers and arrays:
When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the
array. Suppose we declare an array a,
int a[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of a is 1000 and each integer requires two bytes, the five elements will be
stored as follows:
Here variable a will give the base address, which is a constant pointer pointing to the a element of the
array, a[0]. Hence a contains the address of a[0] i.e 1000. In short, a has two purpose - it is the name of the array and
it acts as a pointer pointing towards the element in the array.
Here a is equal to &a[0] by default
We can also declare a pointer of type int to point to the array a.
int *p;
p = a;
// or,
p = &a[0]; //both the statements are equivalent.
Now we can access every element of the array a using p++ to move from one element to
NOTE: You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
A pointer can be used to point to an array, and then that pointer is used to access the array elements.
Program:
#include <stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p ;
p = a; // same as p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d\n", *(p++) );
}
}
Output:
1
2
3
4
5
8
Faculty: Ch.Lavanya Susanna, dept of cse
In the above program, the pointer *(p++) will print all the values stored in the array one by one or *(p+i) can
be used instead of *(p++). We can also use the Base address (a in above case) to act as a pointer and print all the
values.
The statement printf("%d", *(p + i) ); can be replaced with printf("%d", *(a+i) ) then no need to declare a pointer
variable.
C program to find mean of n elements using pointer?
Program:
#include<stdio.h>
int main()
{
int n, i, a[20];
float avg , sum=0;
printf(“enter size of array\n”):
scanf(“%d”,&n);
printf(“enter the elements\n”):
for(i=0; i<n; i++)
{
scanf(“%d”,a+i);
}
for(i = 0; i < 5; i++)
{
sum = sum + *(a+i);
}
avg=sum/n ;
printf("Average = %f \n",avg);
return 0;
}
Output:
enter size of array
5
enter the elements
1
2
3
4
5
Average = 3.000000
Pointer to Multidimensional (2D) Array:
A multidimensional array is of form, matrix[i][j]. The name of the array gives its base address.
In matrix[i][j], matrix will give the base address of this array, even a + 0 + 0 will also give the base address, that is
the address of matrix[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(matrix + i) + j)
which is same as, matrix[i][j]
9
Faculty: Ch.Lavanya Susanna, dept of cse
We can also declare a pointer of type int to point to the 2Darray a.
int a[3][3]
int (*p)[3]; Suppose a is a 2-D array with 3 rows and 3 columns and p is a pointer to an array of 3
integers(columns size), and p contains the base address of array a.
p = a;
// or,
p = &a[0][0]; //both the statements are equivalent.
Program:
#include <stdio.h>
void main()
{
int i;
int a[3][3] = {{1, 2, 3},{ 4, 5, 6}, {7, 8, 9}};
int (*p)[3] =a;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d\t", *(*(p + i) + j));
}
printf(“\n”);
}
}
Output:
1 2 3
4 5 6
7 8 9
In the above program, the pointer *(*(p + i) + j) will print all the values stored in the 2Darray one by one.
We can also use the Base address (a in above case) to act as a pointer and print all the values.
10
Faculty: Ch.Lavanya Susanna, dept of cse
The statement printf("%d", *(*(p + i) + j) ); can be replaced with printf("%d", *(*(a + i) + j) ); then no need to
declare a pointer variable.
Dynamic memory allocation:
Dynamic memory allocation in c language enables the C programmer to allocate memory at
runtime. It can be done by using 4 library functions. They areas follows:
» malloc( )
» calloc( )
» realloc( )
» free( )
To use these functions <stdlib.h> header file must be included in program.
malloc( ) :
• allocates single block of requested memory and contains garbage value if not initialized.
Syntax:
ptr = (castType*) malloc(size);
• Returns a void pointer
• It returns NULL if memory is not sufficient.
• allocates multiple blocks of requested memory and contains zeros if not initialized.
Calloc():
Syntax:
ptr = (castType*) malloc(n, size);
• Returns a void pointer and allocates n no:of continuous memory locations
• It returns NULL if memory is not sufficient.
Example:
int *a;
a= (int *) calloc (10, sizeof(int) ) ;
C Program to read and display array elements using calloc()
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i, n ;
int *p ;
printf("enter no:of elements (size)\n");
scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("enter elements\n");
for(i=0;i<n;i++)
scanf("%d", p+i);
printf("the elements in array are\n");
for (i=0; i<n; i++)
11
Faculty: Ch.Lavanya Susanna, dept of cse
{
printf("%d\n", *(p+i));
}
free(p);
}
Output:
enter no:of elements (size)
5
enter elements
12345
the elements in array are
1
2
3
4
5
Realloc();
• modify the size of previously allocated space.
Syntax:
ptr = realloc(ptr, newsize);
Example:
int *a;
a= (int *) calloc (10, sizeof(int) ) ;
To resize:
a = realloc( a,50);
free():
• releases previously allocated memory.
Syntax:
free(ptr);
Example:
int *a;
a= (int *) calloc (10, sizeof(int) ) ;
To deallocate or release memory : free(a);
Preprocessor commands:
In C program all preprocessor commands begin with a hash symbol (#).A C Preprocessor is just a text
substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. When a
program is compiled, preprocessor commands are executed first and then the program gets compiled.
12
Faculty: Ch.Lavanya Susanna, dept of cse
Some of the preprocessor commands are:
#include: It is used to insert specific header file into C program.
Example:
#include<stdio.h> - This directives tells the preprocessor to get stdio.h from System Libraries and
add the text to the current source file.
#define: It is used to create symbolic constants (known as macros) in C programming language.
Syntax:
#define name constant
Here no need to use semi column at the end of statement
name is the symbolic constant or macro
Example:
#define PI 3.14
Here PI is symbolic constant
C program to find area of a circle:
#include<stdio.h>
#define PI 3.14
void main()
{
double radius, area ;
printf("Enter the radius\n ");
scanf("%lf",&radius);
area = PI *(r*r) ;
printf("area = %ld",area);
}
Output:
Enter the radius
3
area =9.4200000
#undef:It is used to destroy a macro that was already created using #define.
Syntax:
#undef macro
Example:
#undef PI
This undefines the symbolic constant PI
13