What does [i] = * (a_mat + i) do in C?

while( i < a_rows * a_cols ) {
    out[i] = *(a_mat + i);  // this line
    i++;
}

      

What does a dedicated line do?

+2


source to share


2 answers


It gets the value it points to a_mat + i

. Instead, it could have been recorded a_mat[i]

.



+12


source


In C, x[i]

is the same expression as *(x + i)

, because adding an integer to a pointer is done by scaling the integer to the size of the pointer object and because it is defined that way.

This means that, despite its asymmetric form, the indexing operator []

in C is commutative.

A traditional demo of this goes something like this:



main() {
  int x[] = { 1, 2, 3, 4 };

        printf("%d\n", x[2]);
        printf("%d\n", 2[x]);
}

      

Both lines are equivalent and print the same thing.

+3


source







All Articles