0

I have 2D array allocated dynamically using this method: How do we allocate a 2-D array using One malloc statement

#include <stddef.h>

int main() {
        size_t i;
        unsigned int nrows=2;
        unsigned int ncolumns=3;
        int **array; /* Declare this first so we can use it with sizeof. */
        const size_t row_pointers_bytes = nrows * sizeof *array;
        const size_t row_elements_bytes = ncolumns * sizeof **array;
        array = malloc(row_pointers_bytes + nrows * row_elements_bytes);

        int * const data = array + nrows;
        for(i = 0; i < nrows; i++) {
                array[i] = data + i * ncolumns;
                printf("%x\n", data + (i * 3));
        }
}

I understand that array[0] points to 1st 1D array (of 2D array) and array[1] points to 2nd 1D array, but now how to initialize (and access) others member of this 2D array, for instance a[0][1] can be access like?

  array[0] + (char *)1 

It would great, if I may ask for some graphical view of it.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
Milan
  • 1,447
  • 5
  • 19
  • 27
  • 1
    What's wrong with `a[0][1]`? – kaylum Sep 15 '21 at 06:40
  • this solution introduces a bunch of potential problems with alignment. `int` may have different alignment requirements from `int*`. – tstanisl Sep 15 '21 at 09:10
  • @kaylum, but type of a[0] is a pointer and adding 1 to it , is like adding 8 bytes but the next element is at offset 4bytes from a[0] ? – Milan Sep 15 '21 at 12:17
  • Who said anything about adding 1? You have but no one else has. When doing array indexing notation like a[0][1] the compiler will calculate the correct offsets based on the type of the pointer. That's how "pointer arithmetic" works. – kaylum Sep 15 '21 at 12:30
  • @kaylum But a[0][1] is *(a[0] + 1), right? – Milan Sep 15 '21 at 12:45

1 Answers1

1

The main problem is that you read a lot of harmful answers in that other post. You are making everything needlessly slow and complicated. Instead study Correctly allocating multi-dimensional arrays (which has the requested graphical view as "ASCII art").

Fixed code printing some hex data as example:

#include <stdlib.h> // include this!
#include <stdio.h>

int main() 
{
  // memory in C is laid out in rows, so ideally use rows as inner index
  unsigned int col=4;
  unsigned int row=8;
  
  int (*array)[row] = malloc(sizeof(int[col][row]));

  int count=0; // some data
  for(size_t i=0; i<col; i++) 
  {
    for(size_t j=0; j<row; j++)
    {
      array[i][j] = count++;
      printf("%.2X ", array[i][j]);
    }
    printf("\n");
  }
  
  free(array);  // call this!
}
Lundin
  • 195,001
  • 40
  • 254
  • 396