Hacker News new | past | comments | ask | show | jobs | submit login

To elaborate on what tedunangst said, for those less experienced with C:

To some extent it's a matter of nomenclature, but one can draw a distinction in C between arrays of arrays and 2D arrays. It does matter. The following is an array of arrays of ints (a "ragged array" as tedunangst mentioned), if I malloc an array of pointers to ints and then add a loop that mallocs an array of ints for each a[i]:

  int **a;

  a = malloc(N * sizeof(a[0]));
  int i;
  for(i = 0; i < N; i++)
  {
      a[i] = malloc(M * sizeof(a[i][0]));
  }
Then a[i][j] picks out a single int from the array of arrays. The layout in memory is then like this:

      +--+--+--+-       -+--+
  a:  |  |  |  |   ...   |  |   (array of pointers to arrays of ints)
      +--+--+--+-       -+--+
        |   |
        |   |
        |  +--+--+--+-       -+--+
  a[0]: |->| 1| 2| 3|   ...   |  |  (array of ints)
           +--+--+--+-       -+--+
            |
            |  +--+--+--+-       -+--+
  a[1]:     |->|41|42|43|   ...   |  |  (array of ints)
               +--+--+--+-       -+--+
    .
    .	
    .
Note that you cannot rely on these arrays to have any relationship with each other in respect to their positions in memory. That's entirely up to malloc(3).

However, the following is a 2D array of ints:

  int a[3][4];
The same syntax as before can be used to pick out one of the ints in the 2D array: a[i][j]. But this time the C standard gives us that this object is laid out in memory in row-major order. So if you initialize it like this:

  int a[3][4] = { {1, 2, 3, 4}, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
then its memory layout looks like this:

      +--+--+--+--+--+--+--+--+--+--+--+--+
  a:  | 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|
      +--+--+--+--+--+--+--+--+--+--+--+--+
        ^        ^  ^        ^  ^        ^
        |__a[0]__|  |__a[1]__|  |__a[2]__|
This means you can index it manually like this:

  int x = *((int*)a + i * M + j);
where M is the length of each row, in this case M==4. You can't do that with the ragged array-of-arrays.

Exercise: try taking sizeof(a) in both cases, as suggested in the grandparent.

Exercise: 3D arrays?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: