Download presentation
Presentation is loading. Please wait.
Published byJulius Bradley Modified over 9 years ago
1
Lecture 15: Projects Using Similar Data
2
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]; … … a[0] 5 memory 10 15 3 23 a[1] a[2] a[3] a[4] Specifying the type of each element Name of the array The number of the elements
3
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
4
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 The header of the function The size of the array is NOT required. void aFunction( int [ ], int );
5
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. The header of the function
6
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] );
7
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]; A. func( ary[25] ); B. func( ary[] ); C. func( ary ); D. func( ary[0] ); Solution: C
8
Practice Question Q. Which is NOT the right way to pass an integer array argument ary to the following function? #include #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; } A. 1 2 B. 2 4 C. 2 8 D. 1 4 Solution: B
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.