0% found this document useful (0 votes)
7 views13 pages

Adobe Scan Nov 15, 2024

Uploaded by

asmithanalla04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views13 pages

Adobe Scan Nov 15, 2024

Uploaded by

asmithanalla04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter 13: Arrays 217

language provides a capability that enables the programner to


C design a set of similar data types, called array. This chapter
describes how arrays can be created and manipulated in C. Pointers and
artays are very closely related. This relationship is also discussed in this
chapter.

What are Arrays ?


Suppose we wish to arrange the percentage marks obtained by 100
construct 100
students in ascending order.. For this we can either
construct
variables, each variable containing one student's marks; or the
one variable capable of storing hundred students' marks. Otbviously,
easier to handle one variabie than
second alternative is better as it is
handling 100 variables. Such a variable is called an array.
a collection of similar
Now a formal definition of an array-an array is
percentage marks of 100
elements. These similar elements could be
employees. What is
students, or salaries of 300employees, or ages of 50
similar. We cannot have an
important is that the elements must be
5 are floats. Usually, the
array of 10 numbers, of which 5 are ints and
an array of ints or floats
array of characters is called a 'string', whereas
is called simpBy an array.

ASimple Program using Array


marks obtained by a class of 30
Let us write a program to find average
students in a test.
#inciude <stdio.h>
int main()

int avg, Sum = 0;

declaration "/
tt marks[ 30): * array
fur (i =0;1<= 29;it+)

printf ("Enter marks"):


SCant ("%d", &narks|i l); /h store data in array /

for (1 (0;ic= 29;itt)


Surn =sum + marks! ili / resd data trom an àrray*/
218 Let Usc
avg =sum/30;
printf ("Average marks =%din, avg).
retum ;

There is a lot of new material in this program, so let us understatn .


part by part.
Array Dedaration
Lke other variables, an array needs to be declared so that the come
will know what tyDe of an array and how large an array we want. in o
program, we have done this through the statement:
int marks{ 30 :
Here, [30]tells the compiler how many elements of the type int wi be
in our array. This number is often called the 'dimension' of the arra.

Accessing Elements of an Array


Once an array is decdared, an individual element in it is referred us
marks{ 0 ] marks[ 1 ], marks[ 2 1, etc. The number used in []specie:
the elerment's position in the array. Array elements are
counted star ^
from O element. Thus, marks 2 1is not the second element ot té
array, but the third. 0, 1, 2 are often called subscripts and the atä
called subscripted variable. In our program we have used this or
access array elements in two statements
scanf ("%d,&marks[ i]): store data in array "/
Surm =surn +marks[ i]: read data from an arrayi
In the first statement we are passing the address of marks[li]toscanf}
to receive avalue in marks i) In the second statements we are us
marks(i ]to get arunning sum. Since both these statements are use
aloop, each time
through
time we are scanning thealoop,
or using
different value
i takes afrom the array. Thisa
new element
to use variables to
When alil the marks represent
makes arrays 3 * :
subscripts is what
have been added up, the resut is divided by
number of students, to get the
average.
More on Arrays convener:
Let us now discUSs the
features which make arrays so
program. We would also learn the possible pitfalls in usingther.
Chopter 13:Arrays 219

Array Initialization
Look at the following array declarations:
int run{6l=(2,4, 12, 5, 45, 5 ):
nt nË=12,4, 12, 5, 45, 5);
Aoat pressi]={12.3, 34.2, -23.4, -11.3 );
iong int gdp[ 10);
This shows that arrays can be initialized while declaring them. When we
do so, mentioning the dimension of the array is optional, as in arrays n[ ]
and press[]above. Also, note that the array gdp[ ] has auto storage
dass and it has not been initialized, so it contains garbage values. If we
declare it as astatic array,all its elements would be set to 0.
Array Elements in Memory
Consider the following array declaration:

int arr[ 8];


for each of
Ihis would reserve 32 bytes for the array in memory, 4 bytes
the 8 integers. The values in it would be garbage values. The array
elements would occupy adjacent memory locations as shown in Figure
13.1.

12 -45 23 346 77 90
34 66

65508 65516 65520 65524 65528 65532 65536


65512

Tgure 13.1 Layout of an array in memory.


Bounds Checking
Consider the following program:
intincude
main )<stdio.h>
int num[ 40|, i;
tor (i =0;i<=
numi] =i;99;itt)
return 0;
20 Let Usc
We have reserved 40 slots for numí 1, whereas we are attempting to fil,
00 values into it. When value of i goes past 39, the values Would
locations outside the array. If these locations Contain
in then nothing would be lost. But if they contain usetu
be placeddata,
garbage
leading to unpredictable
data, it would be overwritten results. \n
cases, the computer may just
hang. some
message to warn us that we are going
Issue is that there will be no error
beyond the array size. Thus, to ensure that we do not reach beyond the
array size is entirely the programmer's botheration and not that o
compiler.
Passing Array Elements to aFunction
Array elements carn be passed to a function by value, or by refera
These twO calls are illustrated below.

j* Demonstration of call by value &call by reference */


# include <stdio.h>
void display1 ( int );
void display2 ( int * );
int main( )

int i;
int marks[]={55,65, 75, 56, 78, 78, 90 }:
for (i =0; i<= 6; it+ )
displayl ( marks[ i ]) ;
for (i=0 ;i<=6; it+)
display2 (&marks[ i ] ) ;
return 0;

void display1 ( int m)

printf ("%d ", m);


void display2 ( int *n )
{
printf ("%d", *n);

And here is the output...


55 65 75 5678 78 90
Chapter 13:ArrOvs 221

78 go
55 65 75 5678
Here, to display1() we are passing value of an array elerment, whereas
to display2() we are passing address of an array elernent. Since at a
collected
time only one element or its address is being passed, they are
in an integer variable m, or an integer pointer n respectively. Since n
contains the address of array element, to print out the array elernent,
we are usingthe 'value at address'' operator (")
Pointers and Arrays
us first learn
Tobe able to see what pointers have to do with arrays, let
some pointer arithmetic. Consider the folowing example:
#incude <stdio.h
int main)

int i 3, "x;
float j= 1.5, "y:
char k ='c, *z
printf ("Value ofi= %d\n",i);
printf ( "Value of j= %f\n",j):
printf ("Value of k= %c\n", k):
x=&i; y= &j; z =&k;
printf ("Original address inx= %u\n'", x);
printf ("Originaladdress in y= %u\n", y):
printf ("Original address in z = %u\n",z):

printf ("New address inx= 6u\n", x);


printf ("New address in y-"6u\n", y);
printf ("New address in z %u\n 2)
return O;

Here is the output of the program.


Value ofi3
Value of j= 1.500000
Value ofk=C
Original address in x 65524
Original address in y G5520
Originaladdress in z = 65519
New address in
<stdio.h>
#include
{int
main() The (d) (c) performed
(b) (a) andTC/TC++, after
array Similarly,
toTheimportant nteger it Dbserve
inplus New New 222
z
else if4); [4];
k=(arr j=&arr[1];
+&arr[5];
&arr y= x= &i;k= j int int
k=k-3; Addition point way points plus 4,address
(j printf =j+9; &i; =
j program
Comparison
Subtraction
Subtraction z address
to the 65524
printf("The == i=arr[ a points pointer 1. the
( a
tofunction. current to
k) "%d\n", 4, on
pointer result since
y This
/" /* ={10, ", ] given ofearlier points the last
isz=65520 in in
a 1 so y
pointer pointer *k, of of ofpointer:
a int x originalthree =
number and
location immediately
location, is
happens 65524
*x, 20, below two one a can to is
incremented,
two -x); y *y; 30,
number locations. can an 2 lines
pointer
pointer be bytes address
pointers minus plus illustrates to
incremented, beaddress
after
number 45, from a since because of
number 67, from pointer. Thus, effectively long, next th e
variables. iny
point
Same 56, a
the 4 an it output.
these another. locations new points every
*/ 74
pointer.
the current intlocation plus
tot */ it used address is 4,
the }; operations. following can time 65528
always to and
while after
be location. an of a
decremented address pointer
in its 65520 is
the x 4 type. original
location\n") operations passing
current
This
wouldbytes
is a
original
is
four So,
incremertes
long addres.. UscLet
the is be when
; can as location locati addre
entire a 6552(urder
be wel! yer,
Chapter13:Arrays 223

printf ( "Thetwopointers point to different locations\n");


returnO;

already familiar with the operation of addition/subtraction of a


We are
umber to/from a pointer. That brings us to the third operation
subtraction of pointers.
holding
and have been declared as integer pointers and are
addresses of first and fifth element of the array, respectively. Suppose
arr[ 5 ] would be
the array begins at location 65502, then arr[ 1]and
since each integer in
nresent at locations 65506 and 65522 respectively,
expression y-xwould printa
the array occupies 4 bytes in memory. The
are 4 integers apart.
value 4, as y and x are pointing to locations that
both variables point to
Pointer variables can be compared provided
the same data type. Such comparisons can be useful when
objects of
elements of the same array. The
both pointer variables point to inequality. Moreover, a
comparison can test for either equality or
(usually expressed as NULL).
pointer variable can be compared with zero
not attempt the any other operations on pointers, other than the 4
Do never work out.
operations mentioned above... they would

Accessing Array Elements using Pointers


We have learnt these two facts above:
in contiguous memory locations.
(a) Array elements are always stored of
pointer when incremented always points to the next location
(0) A
its type.
correlate these two facts and access array elements using
et us now
pointers.
#include <stdio.h>
int main( )
int num[] ={ 24, 34, 12, 44, 56, 17 };
intptr i,=&num[
ptr; 0): /* assign address of zeroth element/
for (i =0;i<= 5;it+)

pintt ("address = %u element = %d\n". ptr, *ptr );


ptr++; / increment pointer to point to next integer "/
224
Let Us C

retürn 0;

The output of this program would be:


address= 65512 element = 24
address 65516 element = 34
address =65520 element= 12
address=65524 element= 44
address= 65528 element =56
address =65532 element = 17
To understand this output, let us first see how the array elements are
arranged in memory. This is shown in Figure 13.2.

24 34 12 44 56 17

65512 65516 65520 65524 65528 65532

Figure 13.2 Array elements in memory.


In the program, to begin with, we have collected the base address of the
array (address of the 0th element) in the variable ptr using the
statement,
ptr =&num[0]; /* assigns address 65512 to j*/
First time through the loop, ptr contains the address 65512, and tne
value at this address is 24. These are printed using the statement,
printf ("address =9%u element =%d\n" ptr, *ptr ):
of its type
On incrementing ptr, it points to the next memory location element
second
(that is location 65516). But location 65516 contains the second time,it
of the array, therefore when printf()is executed for the 34and
(i.e.,
prints out the second element of the array and its address
65516)..and so on till the last element of the array.
andusing
So now we know how to access array elements using subscript methods
two mfaster
pointer. Obviously, a question arises as to which of the is
should be used when? Accessing array elements by pointers
Chcptet13: Arroys 225

than accessing them by subscripts. However, from the point of view of


anyenience in programming, we shouldobserve the following:
Array elements should be accessed using pointers, if the elements are to
be accessedin afixed order, say from beginning to end, or from end to
heginning, or every alternate element or any such definite logic.
f there is no fixed logic in accessing the elements, it would be easier to
access the elements using asubscript.
Passing an Array to a Function
We already know how to pass individual elements of an array or
addresses of individual elements of an array to a function. Let us now
see how to pass an entire array to a function. Consider the following
program:

* Demonstration of passing an array to a function */


#inciude <stdio.h>
void display1 ( int*, int ) ;
voiddisplay2 (int [], int );
int main{)
int num[]={24, 34, 12, 44, 56,17 );
display1 (&num[ 0], 6);
display2 ( &num[ 0], 6);
return 0 ;

void display1 ( int *ptr, int n)

int i;
for (i =0;i<=n-1;it+)

printf ("element =%d\n", *ptr);point to next element */


to
ptrt+; /* increment pointer

void display2 ( int ptr[0, int n)


int i;
tor (i =0;i<=n-1;it+ )
printf ("element =%d\n'", ptrl i]);
226 Let Us C
Here, the address of the zeroth element and the number of elements in
the array are being passed to the display1() function. The for
accesses the array elements using pointers. Note that it is necessaryloopto
pass the total number of elements in the array, otherwise the functin
would not know when to terminate the for loop.
Same parameters are also being passed to displayz( ). But they are
received in adifferent form

void display2 ( int ptrl ], int n)


Here, though ptr is still an integer pointer, the array notation lets us use
the convenient expression ptr[ i ] to access array elements using
without being required to perform any pointer arithmetic on ptr.
Note that the address of the zeroth element (often called the base
address) can also be passed by just passing the name of the array. Thus,
the following two function calls are same:

display1 (&num[ 0], 6);


display1 ( num, 6);
The Real Thing
If you have grasped the concept of storage of array elements in memory
and the arithmetic of pointers, here is some real food for thought. Once
again consider the following array:
int num[]={24, 34, 12, 44, 56, 17};
base
we getits
We know, that on mentioning the name of the array, thezeroth
address. Thus, by saying *num, we would be able to refer to and
that *num
element of the array, that is, 24. One can easily see
num +0) both refer to 24.
element ofthe
refer the first internally.
Similarly, by using *{ num + 1 ), we can does num+
array, that is, 34. In fact, this is what the C compiler itto
When we say, num[ i ], the Ccompiler internally converts
same:
i). This means that all the following expressions are
i[num)
num[i] *( num +i) *{i+ num)

And here is a program to prove my point.


227

ray elements in dilferent ways *

gtt d et\n" *itnum) i[ um )):

he utout of this prgram would be:


AOSN 65512 eBement 24 24 24 24
AOEsS =6S5I6 element 34 34 34 34
ANTESS =Ées520 eleent 12 12 12 12
adress =5$24element 444 44 44
Aithesy =S528 element = 56 56 56 S6
attress =65532 element 17 17 17 17

Flexible Arrays
we do not know the size of an array at the time of writing the
gam, we can receve t during execution, This is shown tbelow.

scant{"%".Amax ):

This makes the array more flexible, as we do not have to commit to its
tthe tine ef writing the program, This feature has been added in
and woutd be rejected by older complers, as they expect aray
dimension to be apositive non tero integer constànt.
The evariable sized arrays can also be created by using astandard library
hunction malloc ). The following program shows how to use it.
Rexitble artay
$nude <stdio > size
228

includeet

printt{ "%d", pBil}.

eturn 0:

To maiioc( ) function we need to pass the number of bytes toallocate


memory. On doing so, it allocates the bytes and returns the bas
address of the allocated chunk as a void pointer. We need to conver
the void pointer into an int pointer. This conversion is necessary srce
operations cannot be performed on a void pointer. The converson
done using the typecast operation. In the typecast operation the tare
type shouid be enclosed within ( ). Once the address is assigned to p
can be used as a normal array through expression p[i)
Returning an Array
The way an array can be passed to a function, it can also be retue
from the function. This is shown in the program below.
#include <stdio.h>
int* fun (int *nun );
nt mair)

nt nan, p,i
p=tun {&nax)
for(i=0,1<mo i )
printí ("%d", plj}.
return 0;
int fun{ int *num }

Static int arrl ] =( 10, 20, 30, 40, 50)


bopter i Arrays 229

num ssizeof iarr ) /sizeof (arrf 01):


relurn 31

There are a few important points that you should note about the
program:
ia) arr has been declared as static to ensure that it remains alive when
control returns from fun( ) and we can access it in main( .
(b) When we attempt to return the array arr from fun( ) what gets
returned is onlyits base address. Hence return type of fun( ) is int *
ic) Since a function can return only one value, the address of array is
returned explicitly through return statement, whereas the array
size is returned through num using a call by reference.

catein (d) The number of elements in the array is obtained by dividing the
ebase array size bysize of its 0th element.
onvert
Since
sions
P</>Programs
target
Problem 13.1
top,
Wite a program that interchanges elements at odd position with
elements at even position in an array of 10 elements.
eturned Program

You might also like