10 Arrays
10 Arrays
09/02/06
Arrays
1. Static arrays
2. Dynamic arrays.
09/02/06
09/02/06
09/02/06
arrays
09/02/06
arrays
#include<stdio.h>
main( )
{
int marks[54];
/* to find average */
for( j = 0; j < 54; j++ ){
;
}
;
}
09/02/06
Symbolic constants
#include<stdio.h>
#define SIZE 54
main( )
{
int marks[SIZE];
#define is a preprocessing
directive
/* to find average */
for( j = 0; j < SIZE; j++ ){
;
}
;
}
09/02/06
It is used to define
symbolic constants
Preprocessing
/* contents of stdio.h are kept
here */
main( )
{
int marks[54];
#include<stdio.h>
#define SIZE 54
main( )
{
int marks[SIZE];
/* to find average */
for( j = 0; j < SIZE; j++ ){
;
}
Preprocessing
09/02/06
Preprocessor
Simply
/* to find average */
for( j = 0; j < 54; j++ ){
;
}
Preprocessing
09/02/06
int count[5];
count is the name of the array and value of count
is a constant which is the starting address of the
array.
When we say
count[3] = 33;
what happens is 33 is stored in the memory
location whose address is :
(count + 3* sizeof (int))
So, when we pass count to a function, then we
are actually passing an address.
So, the function which uses this address can in
fact modify the original array !
09/02/06
10
Function definition
09/02/06
11
12
void swap(int b[ ])
{
int t;
t = b[0], b[0] = b[1],
b[1] = t;
return;
09/02/06
13
Multi-dimensional arrays
09/02/06
14
2 dimensional array
Number of rows
Declaration
int mat[2][4];
Number of columns
09/02/06
15
09/02/06
16
09/02/06
17
09/02/06
18
int a[4][5];
When you say a[2][3], the location accessed is at
address (a + 2*(5*sizeof(int)) + 3*sizeof(int) )
Let a = 100 and sizeof(int) = 2 then the addresses of
consecutive cells are as:
0
1
2
3
4
0
100 102 104 106 108
1
2
3
09/02/06
110
120
130
int a[4][5];
a is the starting address of the 2 dim. Array
a[k] is the starting address of the k th row
a = 100
a[0] = 100
a[1] = 110
a[2] = 120
100
110
120
130
102
112
122
132
104
114
124
134
106
116
126
136
108
118
128
138
a[3] = 130
09/02/06
20
Function prototype
double f_1(char [ ][4]);
Number of columns in the argument array must be
specified. Otherwise address calculations are not
possible.
Function definition
double f_1(char names[ ][4])
{
;
}
09/02/06
21
Function call
double f_1(char [ ][4]);
main( )
{
char str[10][4];
;
v = f_1(str);
}
09/02/06
22
09/02/06
23
Multi-dimensional arrays
int a[2][4][9];
int b[ ][3][2] = {1,2,3,4,5,6,7};
This can be left blank if
initialization is given
09/02/06