0

I'm working with some C++, and I'd like to understand why the following works.

I have an index:

long long I;

And an array:

double *arr = (double *) malloc(sizeof(double)*100);

It looks like arr + I shifts the index of arr. So, for example, if I=1 then the outcome of this line is arr[1:]. Why is this?

Also, if I have an array of arrays (ex below), what should the shape of I be?

double **arr = (double **) malloc(sizeof(double *)*2);
for (k = 0; k < num_time_series; k++) {
    arr[k] = (double*) malloc(100 * sizeof(double));
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
MadProgrammer
  • 423
  • 1
  • 5
  • 17
  • 2
    For any pointer or array `p` and index `i`, the expression `*(p + i)` is exactly equal to `p[i]`. From that follows that `p + i` is a pointer to the element with index `i`, i.e `p + i` is equal to `&p[i]`. – Some programmer dude Apr 02 '20 at 21:30
  • 1
    And the "array of arrays" you have *isn't* an array of arrays, it's a pointer to the first element of what could be an array, where each element in turn is a pointer. It's commonly called a [*jagged* array](https://en.wikipedia.org/wiki/Jagged_array). – Some programmer dude Apr 02 '20 at 21:32
  • Alright, thanks! So how do I perform *(p+i) for a jagged array? – MadProgrammer Apr 02 '20 at 21:33
  • Exactly the same. For your `arr` if you want to use `arr[i][j]` that's `*(*(arr + i) + j)`. – Some programmer dude Apr 02 '20 at 21:34
  • Yes but I would like to shift all the subarrays at once using j. – MadProgrammer Apr 02 '20 at 21:36
  • @MadProgrammer: Well you can't. You could build another table of pointers, where `shifted[i] = arr[i] + j forall i`, but since the actual contents aren't stored sequentially, there's no way for pointer math to find them all at once. Another option would be to return a proxy object that knows to add an offset (or any other mapping of your choice) when its `operator[]` is invoked. – Ben Voigt Apr 02 '20 at 21:54
  • Does this answer your question? [Difference Between \*(Pointer + Index) and Pointer\[\]](https://stackoverflow.com/questions/4622461/difference-between-pointer-index-and-pointer) – 273K Apr 02 '20 at 21:56

0 Answers0