hkj447
hkj447

Reputation: 737

Using indices with a pointer without dereferencing

I am looking at a function that makes an identity matrix, but I am confused on some of the syntax that is being used.

/* make an identity matrix of ints */
real      **id_mat(int dim) {
    int         row, col;
    real      **mat;

    mat = (real **) alloc2d(dim, dim, sizeof(real));
    if(mat == NULL)
        return (mat);

    for(row = 0; row < dim; row++)
        for(col = 0; col < dim; col++)
            mat[row][col] = (row == col ? 1.0 : 0.0); /* here */

    return (mat);
}

I am confused why mat is not being dereferenced to assign the row/column values. mat stores an address to a pointer, which I presume the goal is to keep the value changed outside of the function, so how does one build an array from an address? Should it not be **mat[row][col] = (row == col ? 1.0 : 0.0);? If not, why does this not work?

Upvotes: 1

Views: 88

Answers (1)

Govind Parmar
Govind Parmar

Reputation: 21562

I am confused why mat is not being dereferenced to assign the row/column values.

mat is indeed being dereferenced with the line:

mat[row][col] = (row == col ? 1.0 : 0.0); /* here */

In C, the syntax a[i] is equivalent to *((a) + (i)), so what you have there is:

*(*((mat) + (row)) + (col)) = ...;

In fact, since addition is commutative (even for addresses), you could just as easily have row[mat][col]. For example, observe the array access syntax as well as the output for the following code:

int a[10][10];
int i = 0;

memset(a, 0, 10 * 10 * sizeof(int));

i[a][5] = 100;

printf("%d\n", 0[a][5]);

Upvotes: 4

Related Questions