|
|
|
|
|
Notice that C must know the length of each row (or what is the same thing, the number of columns) in order to locate an element. C does not need to know the number of rows.
This layout of handling 2-dimensional arrays is the most efficient and uses the least space. It is not the safest way or the most flexible. Java does not support this type of 2-dimensional array.
This type of 2-dimensional array supports ragged arrays, which means that the rows don't all need to be the same length. Here there is an array of pointers to the rows, which can be any 1-dimentional array.
"Ordinary" 2-d array of char | Array of pointers to char |
---|---|
#include <stdio.h> |
#include <stdio.h> |
% lint -m -u subs5.c |
% lint -m -u subs6.c |
The printout on the left is easy to understand, since each "extra" element is just the first element of the next row, as we would expect. For the printout on the right, realize that a compiler can store the arrays x, y, z, u, and v anywhere it wants. From the printout we see that in fact this compiler stored them in reverse order of their declaration: first the 4 locations for u, then the 4 locations for v, then x, then z, then y. At the end of y comes a garbage value.
int s[5][4] = /* or "int s[][4]" */
{ 0, 1, 2, 3,
10, 11, 12, 13,
20, 21, 22, 23,
30, 31, 32, 33,
40, 41, 42, 43
};