Professional Documents
Culture Documents
Arrays
Arrays
11/18/2022 1
Arrays
11/18/2022 2
Initializing arrays (for static arrays)
11/18/2022 3
Initializing character arrays
11/18/2022 4
arrays
11/18/2022 5
arrays
Let the number of
students are increased to
#include<stdio.h> 66
main( )
{
int marks[54]; This should be modified
from 54 to 66
/* to find average */
for( j = 0; j < 54; j++ ){
……;
} This also should be modified.
……;
Like this if at many places 54 is hard coded, then they all
} should be modified to avoid errors. This is a potential problem.
11/18/2022 6
Symbolic constants
#include<stdio.h> #define is a preprocessing directive
#define SIZE 54
main( )
{
int marks[SIZE]; It is used to define
/* to find average */
symbolic constants
for( j = 0; j < SIZE; j++ ){
……;
}
11/18/2022 7
Preprocessing
#include<stdio.h> /* contents of stdio.h are kept
here */
#define SIZE 54
main( )
main( )
{
{
int marks[54];
int marks[SIZE];
/* to find average */
/* to find average */
for( j = 0; j < 54; j++ ){
for( j = 0; j < SIZE; j++ ){ Preprocessor
……;
……;
}
}
……;
……;
}
}
11/18/2022 9
Passing arrays to functions
■ 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 !
11/18/2022 10
Passing arrays to functions
11/18/2022 11
Functions with arrays
11/18/2022 13
Multi-dimensional arrays
11/18/2022 14
2 dimensional array
Number of rows
■ Declaration
❑ int mat[2][4];
Number of columns
11/18/2022 15
2 dimensional arrays: initialization
11/18/2022 16
2 dimensional arrays: initialization
11/18/2022 17
2 dimensional arrays: initialization
11/18/2022 18
2 dimensional arrays: addresses
This is the important number which is collected
from the declaration
■ 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 110 112 114 116 118
2 120 122 124 126 128
3 130 132 134 136 138
11/18/2022 19
2 dimensional arrays: addresses
■ int a[4][5];
11/18/2022 24