tags:

views:

185

answers:

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

What does the marked line do?

+12  A: 

It gets the value of whatever is pointed to by a_mat + i. It could have been written a_mat[i] instead.

Kinopiko
Well, as long as a_mat is declared as an array and whatever it holds has a `sizeof` of 1 byte.
Matthew Scharley
No, `a_mat[i]` and `*(a_mat + i)` are equivalent in all cases because that's how the indexing operator is defined.
jk
@Matthew Scharley Adding 1 to a pointer of type int* will increase the pointer of 4 bytes instead of just one. So *(a_mat + i) is perfectly equivalent to a_mat[i].
Ben
@Ben: ...at least on platforms where `sizeof(int)==4`.
sbi
... Well, now perhaps I know why I had troubles with C.
Matthew Scharley
+4  A: 

In C, x[i] is the same expression as *(x + i), because adding an integer to a pointer is done by scaling the integer by the size of the pointed-to object, and because it's defined that way.

This means that despite its asymmetrical appearance, the indexing operator [] in C is commutative.

The traditional demonstration of this is something like:

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.

DigitalRoss
+1 for mentioning `x[2] == 2[x]` - it's my favorite part of the C language, because it seems unintuitive at first, but after you understand the reasons it makes perfect sense and has a very mathematical symmetry to it.
Chris Lutz