Friendly Fella
Friendly Fella

Reputation: 75

About using pointers for 2D array definition in C

When we're defining a 2D array as in:

int *a[5];

Which dimension does the "5" define? The first or the second?

Upvotes: 0

Views: 103

Answers (2)

John Bode
John Bode

Reputation: 123448

Each a[i] points to a single int, which may be the first element in a sequence of int objects, like so:

 a[0] a[1] a[2] a[3] a[4]
+----+----+----+----+----+
|    |    |    |    |    |
+----+----+----+----+----+
  |    |    |    |    |
  |    |    |   ...  ...
  |    |    +-------------------------------+
  |    +-------------------+                |
  +-------+                |                |
          |                |                |
          v                v                v
        +---+            +---+            +---+
a[0][0] |   |    a[1][0] |   |    a[2][0] |   |
        +---+            +---+            +---+
a[0][1] |   |    a[1][1] |   |    a[2][1] |   |
        +---+            +---+            +---+
         ...              ...              ...

Thus, each a[i] can represent a "row" in your structure. You can dynamically allocate each "row" as

a[i] = malloc( sizeof *a[i] * row_length_for_i );

or you can set it to point to an existing array:

int foo[] = { 1, 2, 3 };
int bar[] = { 5, 6, 7, 8, 9 };
...
a[0] = foo;
a[1] = bar;

As shown in the example above, each "row" may have a different length.

I keep putting scare quotes around "row" because what you have is not a true 2D array - it's not a contiguous sequence of elements. The object immediately following a[0][N-1] will most likely not be a[1][0]. What you have is a sequence of pointers, each of which may point to the first element of a sequence of int, or to a single int, or to nothing at all.

Upvotes: 2

It's not a "2D" array. It's a 1-dimensional array of pointers to int. As such the array size designates that it has space for 5 pointers. Each individual pointer can point to the first element of a buffer with different size.

A "true 2D array" is the colloquial "array of arrays" int a[M][N]. Here the expression a[i] evaluates to the array of N integers, at position i.

Upvotes: 5

Related Questions