I was seeing this post on StackOverflow and saw a new way (at least for me) to define a two dimensional array of 5x5, it works well, but I feel I don't understand what is going on in the background.

The code is.

double (*matrix)[5] = malloc(5 * sizeof *matrix);

How can this define a two dimensional array of 5x5?, before I thought that n mallocs were necessary to produce a n-dimensional array, but apparently I was wrong.

closed as unclear what you're asking by user22815, user40980, durron597, Doc Brown, gnat Oct 31 '15 at 16:05

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • Why do I have downvotes?, at least explain what do you wan't me to fix on the question. – OiciTrap Dec 19 '14 at 22:59
  • 1
    this is too much of an implementation question for this site – raptortech97 Dec 20 '14 at 0:56

matrix is a pointer to a 5-element array of double; this means that the type of the expression *matrix is "5-element array of double"; sizeof *matrix will return the number of bytes required by such an object.

So we're telling malloc to set aside enough memory for 5 5-element arrays of double, and assign the resulting pointer to matrix.

Because of how pointer arithmetic works, matrix points to the first 5-element array, matrix + 1 points to the second 5-element array, matrix + 2 points to the third 5-element array, etc.

Since a[i] is equivalent to *(a + i), the expression matrix[i] gives us the i'th 5-element array, so matrix[i][j] gives us the j'th element of the i'th 5-element array.

Not the answer you're looking for? Browse other questions tagged or ask your own question.