Download presentation
Presentation is loading. Please wait.
Published byArabella Jefferson Modified over 8 years ago
1
C Programming Lecture 15 Two Dimensional Arrays
2
Two-Dimensional Arrays b The C language allows arrays of any type, including arrays of arrays. With two bracket pairs, we obtain a two- dimensional array.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 char name[3][12]A 2-dimensional array capable of storing 3 names each with up to 11 characters and the null character.
3
How the Elements of a Two-Dimensional Array are Stored b 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.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.However, it is often convenient to think of a two-dimensional array as a rectangular collection of elements with rows and columns.
4
Example of Conceptual Storage of a Two-Dimensional Array b 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 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.
5
Passing a Two-Dimensional Array to a Function b 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.So the compiler can determine the correct storage mapping function.
6
Example of a Function Call and 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; int i, j, sum = 0; for (i = 0; i < 3; ++i) for (i = 0; i < 3; ++i) for (j = 0; j < 5; ++j) sum += a[i][j]; sum += a[i][j]; return sum; return sum;}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.