1

Im looking for a way to fill up a multi-d array with numbers gotten from a text file. I have an array(?) dynamically created, but im not sure how to make it multidimensional.

basically the text document has a set of numbers, user input decides the amount of columns and rows of a matrix, and i need to fill that matrix with numbers from the text document. Any help is appreciated

ptrm2 = (int*)malloc(size2 *sizeof(int));

Drax
  • 141
  • 8
  • 2
    Take a look at [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). If you declare the array as shown in the answer, as one adjacent chunk of memory, then you can just fread/fwrite the whole array in one go. – Lundin Oct 07 '19 at 13:27
  • To make a multidimensional array with `malloc`, either you allocate an array of pointers for the rows, and then allocate each of them separately for the columns, or you allocate a single-dimensional array with as many cells as you need in total and then use arithmetic to map multi-dimensional coordinates to the correct cell (e.g., `row * height + column`). – Arkku Oct 07 '19 at 13:29
  • There are probably 37,292 duplicates of this question -- do we have a canonical one to point to? – Steve Summit Oct 07 '19 at 13:42
  • @Steve - depends on how you separate the dupes: (1) in order of using "multidimensional" or (2) in order of using "allocate!" – Adrian Mole Oct 07 '19 at 14:53

1 Answers1

1

You can allocate a two-dimensional array in two stages, as follows (I'm assuming that the base data type is int here, but it could be almost anything):

int** my2dArray = malloc(sizeof(int*) * n_rows); // Makes one INTEGER POINTER for each of n_rows
for (int n = 0; n < n_rows; ++n) my2dArray[n] = malloc(sizeof(int) * n_cols); // Makes one INTEGER for each column

You can then access any element of the 2-D array, given its row and column with, for example:

int value = my2dArray[row][column];

Here, I've assumed the conventional (standard) approach of using "row priority" (so that the first index is the row).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83