80 likes | 144 Views
Lecture 15: Projects Using Similar Data. memory. …. Name of the array. a[0]. 5. a[1]. 10. a[2]. 15. a[3]. 3. Specifying the type of each element. The number of the elements. a[4]. 23. …. What is an Array?.
E N D
memory … Name of the array a[0] 5 a[1] 10 a[2] 15 a[3] 3 Specifying the type of each element The number of the elements a[4] 23 … What is an Array? • An array is a data structure consisting of related data items of the same type. • Stored in a group of memory locations • Defining arrays int arrayName[ 100 ]; • Examples int a[5]; float b[120], x[24];
Passing Arrays to Functions • The name of an array evaluates to the address of the first element of the array. • Passing arrays • To pass an array argument to a function, specify the name of the array without any brackets int anArray[100]; aFunction( anArray, 100 ); • Array size usually passed to function • Function knows where the array is stored • Modifies original memory locations
The header of the function The size of the array is NOT required. Defining Function with Array Parameters • The function’s parameter list must specify that an array will be received. void aFunction( int ary[ ], int size ) { …….. } • Function prototype void aFunction( int ary[ ], int size ); • Parameter names optional in prototype • int ary[ ] could be written int [] • int size could be simply int void aFunction( int [ ], int );
The header of the function Defining Function with Array Parameters • Using the type qualifier const. void aFunction( const int ary[ ], int size ) • The modification of the array elements are NOT allowed. • Any attempt to modify an element of the array in the function body results in a compile-time error.
Passing Array Elements • Passed by call-by-value. • Array elements are like normal variables • Pass subscripted name to function void modifyArrayElement( int arrayElement ); int array[ 10 ] = {0}; modifyArrayElement( array[1] ); modifyArrayElement( array[8] );
Practice Question Q. Which is the right way to pass an integer array argument ary to the following function? void func( int a[] ); int ary[25]; func( ary[25] ); func( ary[] ); func( ary ); func( ary[0] ); Solution: C
Practice Question Q. Which is NOT the right way to pass an integer array argument ary to the following function? #include<stdio.h> #define SIZE 5; void func( int a[], int x ); int main( void ) { int b[SIZE] = {1, 2, 3, 4, 5}; func(b, b[1]); printf(“%d %d\n”, b[0], b[1]); return 0; } void func( int a[], int x) { int k; for (k = 0; k < SIZE; k++) a[k] *= 2; x *= 2; } 1 2 2 4 2 8 1 4 Solution: B