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));

4
  • 2
    Take a look at 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. Commented Oct 7, 2019 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). Commented Oct 7, 2019 at 13:29
  • There are probably 37,292 duplicates of this question -- do we have a canonical one to point to? Commented Oct 7, 2019 at 13:42
  • @Steve - depends on how you separate the dupes: (1) in order of using "multidimensional" or (2) in order of using "allocate!" Commented Oct 7, 2019 at 14:53

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.