C++ Logo


Advanced search

[wg14/wg21 liaison] Multidimensional subscript operator

From: Uecker, Martin <Martin.Uecker_at_[hidden]>
Date: Sun, 25 Apr 2021 07:26:55 +0000

Just a small comment on P2128R3. There is says

"generic interoperability with C-style pointer-to-pointer
arrays c"

I assume this refers to code like this to creat
something which looks like a multi-dimensional array:

double **x = xmalloc(N * sizeof(double*));

for (int i = 0; i < N; i++) {

  x[i] = xmalloc(M * sizeof(double));

  for (int j = 0; j < M; j++)
    x[i][j] = 0.;

I just want to point out that this is not how we
would do this in C since at least C99. Instead
we write:

double (*x)[M] = xmalloc(sizeof(double[N][M]));

x[i][j] = 0.;

or sometimes (to more clearly differentiate
between pointers and arrays):

double (*xp)[N][M] = xmalloc(sizeof *xp);

(*xp)[i][j] = 1.;

With this, you the multi-dimensional array is
a single object and one also gets run-time bounds
checking for free if the compiler supports this.


Received on 2021-04-25 02:27:02