1 / 6

Two-Dimensional Arrays in C Programming

Learn about two-dimensional arrays in C programming: how they are stored, conceptual storage visualization, and passing them to functions.

jmoffett
Télécharger la présentation

Two-Dimensional Arrays in C Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C Programming Lecture 15 Two Dimensional Arrays

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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; }

More Related