0% found this document useful (0 votes)
27 views32 pages

Module-4 Arrays and Pointers

Uploaded by

Triveni Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
27 views32 pages

Module-4 Arrays and Pointers

Uploaded by

Triveni Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

MODULE-4

ARRAYS AND POINTERS


Why Arrays?

Consider a situation, where we need to store 5 integer numbers. If we use simple


variable and data type concepts, then we need 5 variables of int data type and program will be
something as follows:

#include<stdio.h>
void main()
{
int number1;
int number2;
int number3;
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
printf( "number1: %d \n", number1);
printf( "number2: %d \n", number2);
printf( "number3: %d \n", number3);
printf( "number4: %d \n", number4);
printf( "number5: %d ", number5);
}
It was simple, because we had to store just 5 integer numbers. Now let's assume we have to
store 5000 integer numbers, so what is next???

To handle such situation, C language provides a concept called the ARRAY

Examples where arrays can be used are

 List of temperatures recorded every hour in a day, or a month, or a year


 List of employees in an organization
 List of products and their cost sold by a store
 Test scores of a class of students
Definition of an Array:-Array is a collection of elements of same data type.
The elements are stored sequentially one after the other in memory.
Any element can be accessed by using
→ name of the array

→ position of element in the array (index)

Types of array

 Single dimensional array or One dimensional array


 Two dimensional array
 Multi dimensional array

Single Dimensional Array :- An Array which has only one subscript is known as Single
dimensional array or One dimensional array

The individual array elements are processed by using a common array name with different
index values that start with Zero and ends with array_size-1

Syntax of Declaring Single Dimensional Arrays

data_type array_name[array_size];

where

data_type: can be int, float or char

array_name: is name of the array

array_size : an integer constant indicating the maximum number of data elements to be stored.

Example: int a[5];

Here a is an Integer Array that can hold up to 5 values in it.

Array Representation
Here

a[0] holds the first element in the array

a[1] holds second element in the array

a[2] holds third element in the array

and so on..

Memory occupied by 1D array

Total memory=array size * size of datatype


For example :int a[5];
Total memory =5*sizeof (int)
= 5*2
=10 bytes.

Storing Values in Arrays


The values can be stored in array using following methods:
 Static initialization
 Initialization of array elements one by one.
 Partial initialization of array
 Array initialization without specifying the size
 Run Time array Initialization
1. Static initialization:- We can initialize the array in the same way as the ordinary values
when they are declared.

The general syntax of initialization of array is

data_type array_name[array_size]= {List of values};

Example:

int b[4]={10,12,14,16};

Here each value will be stored in respective index values of the array.
i.e in location b[0] we store the value 10, in location b[1] we store the value 12 and so on…

Suppose if we try to insert more values then the size of the array it will give us an error “Excess
elements in array initializer”

Example:

int b[4]={10,12,14,16,18};

Here the size of the array b is 4 but we are trying to store 5 values hence we will be getting the
error in this case.

2. Initialization of array elements one by one:- Here the user has the liberty to select the
locations and store values and the array. This type of initialization is not used much practically

Example

int b[4];

b[0]= 10;

b[2]=14;

Only the array locations specified by the user will contain the values which the user wants the
other locations of array will either be 0 or some garbage value.
3. Partial initialization of array :- If the number of values initialized in the array is less than
the size of the array then it is called partial initialization. The remaining locations in the array
will be initialized to zero or NULL(‘\0’) value automatically

Example:

int b[4]={10,12};

Here the remaining locations in the array will be initialized to zero.

4. Array initialization without specifying the size :- Here the size or the array is not specified
by the user, the compiler will decide the size based on the number of values declared in the
array.

Example:

int b[ ]={6,12,18};

Here the size of the array is specified and the compiler will set the array size as 3 for this
example

5. Run Time array Initialization:- If the values are not known by the programmer in advance
then the user makes use of run time initialization. It helps the programmer to read unknown
values from the end users of the program from keyboard by using input function scanf().
Here we make use of a looping construct to read the input values from the keyboard and store
them sequentially in the array.
Example: /* C program to demonstrate run time initialization*/
#include<stdio.h>
void main()
{
int b[5],i;
printf(“Enter 5 elements\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&b[i]);
}
}

Accessing array elements:

Eg: int b[5]={12,14,16,18,20};

We can access the elements of array using index or subscript of element. An index gives the
portion of element in the array .To access an array element make use of array_name[index]

To access value 16 we write b[2]=16 similarly if we wish to print the value 18 we write
printf(“%d”,b[3]);

Programming examples on one dimensional array:

1. Write a C program to read and print n integer elements in an array.

#include<stdio.h>
void main()
{
int a[20 ],n,i;
printf(“Enter the array size”);
scanf(“%d”,&n);
Printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“The elements entered in the array are\n”);
for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
}
}

2. Write a c program to display first n natural numbers in an array.

#include<stdio.h>
void main()
{
int a[20 ],n,i;
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
printf(“The first %d natural numbers are:\n”,n);
for(i=0;i<n;i++)
{
a[i]=i+1;
printf("a[%d]=%d\n",i,a[i]);
}
}

3. Write a c program to add two one dimensional array

include<stdio.h>
void main()
{
int a[20 ],b[20],c[20],n, i;
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter the elements of Array A\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the elements of Array B\n”);
for(i=0;i<n;i++)
scanf(“%d”,&b[i]);
printf(“Array Addition\n”);
for(i=0;i<n;i++)
c[i]=a[i]+b[i];
printf(“The resultant array is \n”);
for(i=0;i<n;i++)
printf(“%d\n”,c[i]);
}
4. Write C program to find largest and smallest number in an array of n elements

include<stdio.h>
void main()
{
int a[10 ],n,i,max,min
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
printf(“Enter the values \n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
max=min=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf(“Largest number=%d\n”,max);
printf(“Smallest number=%d\n”,min);
}

5. Write a C program to read n integer elements in an array and print the same in
reverse order.

#include<stdio.h>
void main()
{
int a[20 ],n,i;
printf(“Enter the array size”);
scanf(“%d”,&n);
Printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“The elements entered in the array are\n”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
printf(“The elements of the array in reverse order are\n”);
for(i=n-1;i>=0;i--)
printf(“%d\t”,a[i]);
}
6. Write a C Program to find the sum of odd, even, all and average of n numbers using
arrays
#include<stdio.h>
void main()
{
int a[20 ],sum=0,esum=0,osum=0,n,i;
float avg;
printf(“Enter the array size”);
scanf(“%d”,&n);
printf(“Enter the array elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
if((a[i]%2)==0)
esum=esum+a[i];
else
osum=osum+a[i];
}

avg=sum/n;
printf(“The sum of all numbers is %d”,sum);
printf(“The sum of even numbers is %d”,esum);
printf(“The sum of odd numbers is %d”,osum);
printf(“The average of all numbers is %f”,avg);
}

7. Write a C Program to generate Fibonacci series using arrays

#include<stdio.h>
#include<conio.h>
void main()
{
int fib[20],n,i;
printf(“Enter the no. of Fibonacci series to be generated\n”);
scanf("%d",&n);
fib[0]=0;
fib[1]=1;
if(n==1)
printf(“fibonacci series is %d”,fib[0]);
else if(n==2)
printf(“fibonacci series is %d \t %d”,fib[0],fib[1]);
else
for(i=2;i<n;i++)
{
fib[i]=fib[i-1]+fib[i-2];
}
printf(“The fibonacci series are :\n");
for(i=0;i<n;i++)
{
printf("%d\t",fib[i]);
}
}

Sorting Techniques:-

The Process of arranging the elements in ascending or descending order is called sorting

Bubble sort: The sorting algorithm is a comparison based algorithm in which each pair of
adjacent elements is compared and the elements are swapped if they are not in order. This
algorithm is not suitable for large datasets as its average and worst case time complexity are of
O(n2). where n is the number of items.

/*C program to sort n numbers using Bubble sort*/

#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("The entered elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n***** SORTING ******\n");
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}

Selection sort: This is an in-place comparison based algorithm It is comparison based


algorithm in which list is divided into 2 parts. The sorted part at left and unsorted part at right
end. Initially sorted part is empty and unsorted part is entire list.The smallest element is taken
from the unsorted array and swapped with the leftmost element and the element becomes the
part of sorted array.

/*C program to sort numbers in ascending order using selection sort technique*/

#include<stdio.h>
void main()
{
int a[20],n,i,j,temp;
printf("Enter total elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("The sorted elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}

Searching Techniques:

The process of finding a particular element in the large amount of data is called searching.

Linear search:- A Linear search is also called as sequential Search. In this technique we search
for a given specific element called as key element in the large list of data in sequential order. If
the key element is present in the list of data then the search is successful otherwise search is
unsuccessful.

Benefits:

• Simple approach
• Works well for small arrays
• Used to search when the elements are not sorted
Disadvantages:

• Less efficient if the array is large


• If the elements are already sorted, linear search is not efficient.

/*C program to search an element in an array using linear search*/

#include<stdio.h>
void main()
{
int a[100],n,i,key,flag=0;
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter %d elements ",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched\n" );
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
flag=1;
break;
}
}
if(flag= =1)
printf("Element found at position %d\n", i+1);
else
printf("Element not found\n");
}

Binary Search: It is fast search algorithm which works on the principle of divide and conquer.
for this algorithm to work properly the data collection should be in the sorted form

1. Divides the array into three sections:

– middle element

– elements on one side of the middle element

– elements on the other side of the middle element

2. If the middle element is the correct value, done. Otherwise, go to step 1. using only the
half of the array that may contain the correct value.

3. Continue steps 1. and 2. until either the value is found or there are no more elements to
examine

Advantages:

• Very efficicent searching technique.

Disadvantages:

• Array element should be sorted.

C program to search an element in an array using Binary search

#include<stdio.h>
void main()
{
int a[100],n,i,low,high,mid,key,flag=0;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter %d elements in ascending order\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched\n" );
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
flag=1;
break;
}
else
if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if(flag= =1)

printf("Element found at position %d\n", mid+1);


else
printf("Element not found\n");
}

Two dimensional array


The simplest form of multidimensional array is two dimensional array. Arrays with two or more
dimensions are called multi-dimensional arrays. (in terms of rows and columns) of same data
type or An array which has two subscripts are known as two dimensional arrays. The first
subscript represents rows and the second subscript represent column.

Syntax:

data_type array_name[size1][size2];

where,

data_type: is the type of data to be stored and processed in the computer’s memory

array_name: is a valid identifier representing name of the array


[size1]: indicates number of rows in the array

[size2]: indicates the number of columns in the array.

Example:

int a[2][3];

Represents a is a two dimensional integer array that holds two rows and three columns.

Initialization of two dimensional array :

1)Initializing all elements row wise:- A multidimensional array can be initialized by specifying
bracketed values for each row.

Example:

int[2][3]={{5,3,4} {6,1,2}} ;

this initialization can also be written as int a[2][3] ={5,3,4,6,1,2}

Accessing two dimensional array elements:- An element in a two dimensional array is


accessed by using the subscripts i.e. row index and column index of the array.

The feasible way of accessing elements in a two dimensional array is by using nested loops.
Reading and printing 2 dimensional array:-
Reading 2D array
where m-rowsize, n-columnsize, i-row index and j-column index
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}

Printing 2D array
where m-rowsize, n-columnsize, i-row index and j-column index
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d", a[i][j]);
}
printf(“\n”)
}

Programming examples on Two dimensional array:

1. Write a c program to read and print the matrix of m rows and n columns

#include<stdio.h>
void main()
{
int a[20 ][20]m,n,i,j;
printf(“enter the row and column size\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
printf(“The elements of matrix are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t", a[i][j]);
}
printf(“\n”);
}
}

Output
Enter the row and column size
23
Enter the elements of matrix
3 4 5 9 10 12
The elements of matrix are

3 4 5

9 10 12

2. Write a C program to perform addition of two matrices

include<stdio.h>
void main()
{
int a[20 ][20],b[20][20],c[20][20],m,n, i,j;
printf(“enter the rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the elements of Matrix B\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“Matrix Addition\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“The resultant matrix is\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\n”,c[i]);
}
printf(“\n”);
}
}

3. Write a C Program to find Transpose of matrix

include<stdio.h>
void main()
{
int a[20 ][20],b[20][20], m,n, i,j;
printf(“enter the rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the elements of Matrix are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“Matrix Transpose\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[j][i]=a[i][j];
}
}
printf(“The Transpose of the matrix is \n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
}

4. Write a C Program to print Diagonal elements of the matrix

include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j;
printf(“enter the no rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Matrix A is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“The diagonal Elements are\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
printf(“%d”,a[i][j]);
}
}
printf(“\n”);
}
}

5. Write a C Program to find sum of the the rows and columns of given matrix

#include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j,sum;
printf(“enter the no rows and column of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Martix A is Displayed as \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum=sum+a[i][j];
}
printf(“sum of the elements of row %d in matrix=%d”,i,sum);
}
for(i=0;i<m;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum=sum+a[j][i];
}
printf(“sum of the elements of column %d in matrix=%d”,i,sum);
}

6. Write a C Program to find sum of the Diagonal elements of the matrix

#include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j,sum=0;
printf(“enter the order of matrix”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Martix A is Displayed as \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
for(i=0;i<m;i++)
{
sum=sum+a[i][i];
}
printf(“The sum of the diagonal elements of matrix=%d\n”,sum);
}

7. Write a C Program to find the largest element in given matrix

#include<stdio.h>
void main()
{
int a[20 ][20], m,n, i,j,large;
printf(“enter the order of matrix\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Martix A is Displayed as \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}

large=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>large)
large=a[i][j];
}
}
printf(“The largest element in the matrix = %d\n”,large);
}

Multidimensional array
An array having 3 or more subscript or dimensions is known as multidimensional array.
It is also known as arrays of arrays or matrix.
The general form of multidimensional array is
data_type array_name[s1][s2][s3]….[sn];
Where s1 is the size of ith dimension.
Representation of Multidimensional Array
POINTERS
Pointers: A pointer is a variable that holds the address of another variable. The pointer variable
contains only the address of the referenced variable not the value stored at that address.

Some of the advantages of using pointers are as follows


1. Pointers are more efficient in handling arrays and data tables
2. Pointers are used with function to return multiple values
3. Pointers allow C to support dynamic memory management
4. Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked list, stacks, queues, trees etc
5. Pointers reduce length and complexity of program
6. Pointers reduce program execution time and saves data storage space in memory

Disadvantages of pointers
1. One of the disadvantage of using pointer is that program may crash if sufficient memory
is not available at run time to store pointers.

Pointer uses two basic operators


1. The address operator (&): It gives address of an object
2. The indirection operator (*):It is used to accesses the object the pointer points to.

Declaring a pointer variable:


The general syntax of declaring pointer variable is

Datatype *ptrname;
Data type: It specifies the type of the pointer variable that you want to declare like (int, float,
char, double or void)
* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the
name of the pointer variable.

Example: int *p; // declares a pointer variable p of integer type


float *temp;// declares a pointer variable temp of float data type

Initialization of pointer variable: Similar to the initialization of other variables at the time of their
declaration, you can also initialize the pointer variable by assigning address of othervariables to
them.
Syntax
Datatype *ptrname = expression;
Where
Datatype: It can be any basic data type,
ptrname is a pointer variable
expression can be any constant value or any variable containing value.
Example 1:
int a;
int *ptr = &a; //address of a is stored in ptr variable .
Example 2:
float temp; // temp is a variable of float type
float *p; //p is a ptr variable pointing to float type
p=&temp; // pointer variable p holds the address of temp
program to illustrate declaration and initialization
Example:
#include<stdio.h>
void main()
{
int *ptr; / /declaration ofpointer variable
int a=10;
ptr=&a; / /initialization of pointer variable
printf(“the value of a=%d\”,a);
printf(“the value of a using pointer=%d\n”,*ptr);
printf(“the address of a=%u\n”,ptr);
}
Output:
The value of a=10
The value of a using pointer=10
The address of a =32200

Using the address of (&) operator: A computer uses memory to store the instructions of different
programs and the values of different variables. Since memory is a sequential collection of storage
cells, each cell has an address. When you declare a variable, the operating system allocates memory
according to the size of the data type of that variable. In this memory location, the value of the
variable is stored.

Example : int a=100;

This statement request the operating system to allocate two bytes of space in memory and stores 100
in that location.
a ------------ variable name

100 ------------value of the variable

1500 ----------  the address of the memory location

By using the address of (&) operator, you can determine the address of a variable.
#include<stdio.h>
Void main()
{
int a=100,*ptr1;
float b=12.6, *ptr2;
ptr1=&a;
ptr2=&b;
printf(“the address of a = %u and its value is%d\n”,ptr1,*ptr1);
printf(“the address of b =%u and its value is %f\n”,ptr2,*ptr2);
getch();
}
Output: the address of a=2600 and its value is 100
The address of b=4876 and its value is 12.600000

Pointers and functions (call by reference) arguments:


The call by reference method allows you to copy the addresses of actual arguments of the calling
function to the formal arguments of the called function. In this method the pointers are passed as
arguments to the functions. When you change the values in the functions, the original values of the
actual parameters are also changed. Following program illustrate use of call by reference.

#include<stdio.h>
void swap(int *a, int *b);
void main()
{
int x,y;
x=100;
y=200;
printf(“before swap: x=%d\n y=%d\n”x,y);
swap(&x,&y);
printf(“after swap: x=%d\n,y=%d\n”,x,y);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

Output:
Before swap: x=100
y=200
After swap: x=200
y=100
Pointers and arrays: Arrays are closely related to pointers in C programming but the important
difference between them is that, a pointer variable can take different addresses as value
whereas, in case of array it is fixed. This can be demonstrated by an example:

#include <stdio.h>
void main()
{
char c[4];
int i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);
}
}
Notice, that there is equal difference (difference of 1 byte) between any two consecutive elements
of array.

Note: You may get different address of an array.

Relation between Arrays and Pointers


Consider and array:

int arr[4];

In arrays of C programming, name of the array always points to the first element of an array.
Here, address of first element of an array is &arr[0]. Also, arr represents the address of the
pointer where it is pointing. Hence, &arr[0] is equivalent to arr.

Address in arrays Address in pointes Value in arrays Value in pointers


&a[0] (a+0) a[0] *(a+0)
&a[1] (a+1) a[1] *(a+1)
&a[2] (a+2) a[2] *(a+2)
&a[3] (a+3) a[3] *(a+3)
&a[4] (a+4) a[4] *(a+4)
……. ………. …….. ………
&a[i] (a+i) a[i] *(a+i)
//C Program to find the sum of 10 marks with arrays and pointers.
#include <stdio.h>

void main()
{
int i,marks[10],sum=0;
printf("Enter 10 marks:\n");
for(i=0;i<10;++i)
scanf("%d",(marks+i));
for(i=0;i<10;++i){
sum += *(marks+i);
}
printf("Sum=%d",sum);
getch();
}
Output
Enter 10 marks:
2 3 4 5 3 5 7 10 21 28
Sum=88

Pointer Arithmetic
Pointer arithmetic is very important to understand, if you want to have complete knowledge of
pointer. In this topic we will study how the memory addresses change when you increment a pointer.

16 bit Machine
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is always 2 bytes.
But when we perform any arithmetic function like increment on a pointer, changes occur as per the
size of their primitive data type.
Size of datatypes on 16-bit Machine :

Type Size(bytes)

int or signed int 2

Char 1

Long 4

Float 4

Double 8

long double 10
Examples for Pointer Arithmetic
Now lets take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it will increment by 2
bytes because int is also of 2 bytes.

float* i;
i++;
In this case, size of pointer is still 2 bytes. But now, when we increment it, it will increment by 4
bytes because float is of 4 bytes.

double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we increment it, it willincrement
by 8 bytes because its data type is double.
Pointers to Pointer
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>
void main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
getch();
}
Output:
Value of var = 3000
Value available at *ptr = 3000 Value
available at **pptr = 3000

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";
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.
Consider the following array of strings
char name[3][25]; //name is a table containing three names of maximum length 25(including null
character. Total storage is 75 bytes.
We may encounter rarely all the individual strings of length equal to 25. Therefore instead
of making each row fixed number of characters, we can make it a pointer to a string of varying length.
For example
char *name[3]={
"Bangalore",
"Chennai",
"Mangalore"
};
Declares name to be an array of three pointers to character, each pointer pointing to a particular
name as
Name[0] --------- Bangalore
Name[1] ---------Chennai
Name [2] -------- Mangalore
This declaration allocates only 28 bytes, sufficient to hold all characters. Whereas using array of
strings , same array without using pointer needs 75 bytes.
char name[3][25]= {
"Bangalore",
"Chennai",
"Mangalore"
};

Initialization of Pointer Arrays


Consider the problem of writing a function month_name(n), which returns a pointer to a character
string containing the name of the n-th month. This is an ideal application for an internal static array.
month_name contains a private array of character strings, and returns a pointer to theproper one when
called. This section shows how that array of names is initialized.
/* month_name: return name of n-th month */
char *month_name(int n)
{
static char *name[] = {
"Illegal month",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
return (n < 1 || n > 12) ? name[0] : name[n];
}
The declaration of name, which is an array of character pointers, The initializer is a list of
character strings; each is assigned to the corresponding position in the array. The characters of
the i-th string are placed somewhere, and a pointer to them is stored in name[i]. Since the size of
the array name is not specified, the compiler counts the initializers and fills in the correctnumber.

Function returning Pointer


A 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, hence if you return a pointer
connected to a local variable, that pointer be will pointing to nothing when function ends.
#include <stdio.h>
#include <conio.h>
int* larger(int*,
int*);void main()
{
int
a=15
; int
b=92
; int
*p;
p=larger(&a, &b);
printf("%d
islarger",*p);
}

int* larger(int *x, int *y)


{
if(*x >
*y)
return
x; else
return y;
}

You might also like