60 likes | 85 Views
Learn about two-dimensional arrays in C programming: how they are stored, conceptual storage visualization, and passing them to functions.
E N D
C Programming Lecture 15 Two Dimensional Arrays
Two-Dimensional Arrays • The C language allows arrays of any type, including arrays of arrays. • With two bracket pairs, we obtain a two-dimensional array. int a[100]; A 1-dimensional array capable of storing 100 integers. int b[2][7]; A 2-dimensional array capable of storing 2 rows with 7 integers in each row. char name[3][12] A 2-dimensional array capable of storing 3 names each with up to 11 characters and the null character.
How the Elements of a Two-Dimensional Array are Stored • A j x k dimensional array has j * k elements. • Starting with the base address of the array, all the elements are stored contiguously in memory. • However, it is often convenient to think of a two-dimensional array as a rectangular collection of elements with rows and columns.
Example of Conceptual Storage of a Two-Dimensional Array • If we declare: int a[3][5]; we can think of the array elements arranged as: col 1 col 2 col 3 col 4 col 5 row 1 a[0][0] a[0][1] a[0][2] a[0][3] q[0][4] row 2 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4] row 3 a[2][0] a[2][1] a[2][2] a[2][3] a[2][4] Note that the row is specified by the first index and the column by the second index.
Passing a Two-Dimensional Array to a Function • When a multidimensional array is a formal parameter in a function definition, all sizes except the first must be specified: • So the compiler can determine the correct storage mapping function.
Example of a Function Calland Function Definition Array Declaration: int ary[3][5], result; Function Call: result = sum(ary); Function Definition: int sum(int a[][5]) { int i, j, sum = 0; for (i = 0; i < 3; ++i) for (j = 0; j < 5; ++j) sum += a[i][j]; return sum; }