0

I need an array where each member has 3 elements of the same type. I can use an array of structs, or a 2 dimensional array.

// Array of structs:
struct point {  double x, y, z; };
struct point path[20000];  
// Now access z by
path[i].z
// 2-dimensional array:
double path[20000][3];
// Access z by
path[i][2]

Which method is most efficient? Or are they the same?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Peter R
  • 1
  • 4
  • Efficiency is really hard to talk about in the abstract, because different approaches, and different trade-offs. In this case, they're about the same, but the named `x`/`y`/`z` fields read way better. Plus, the `Point` abstraction is just really useful overall – Alexander Sep 17 '20 at 18:11
  • That's not a two-dimensional array. [What are the differences between a multidimensional array and an array of arrays?](https://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays) – John Wu Sep 17 '20 at 19:26
  • I'd venture to suggest that, unless you're trying to save bytes or microseconds, you should use the version that has most expressive power. Someone has to maintain this stuff, after all. – Kevin Boone Sep 17 '20 at 19:29

2 Answers2

0

There's no difference.

If I remember correctly, in theory a compiler is allowed to insert padding bytes between the members of struct point, but no sane compiler would do it in this case.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

struct point { double x, y, z; }; may incur padding - although quite unlikely.
double path[20000][3]; has no padding.

In this case, I recommend to code for clarity.
Since the comment hints that the access is of z, use .z rather than [2]

// Now access z by
path[i].z
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256