user3346223
user3346223

Reputation: 29

How is this code correct?

I have downloaded a code, it looks correct (and runs):

int (*oldMatrix)[NJ] = new int[NI][NJ];
int (*newMatrix)[NJ] = new int[NI][NJ];

/*  initialize elements of old to 0 or 1 */
for (i=1; i<=NI; i++) {
    for (j=1; j<=NJ; j++) {
        x = rand()/((float)RAND_MAX + 1);
        if(x<0.5) {
            oldMatrix[i][j] = 0;
        } else {
            oldMatrix[i][j] = 1;
        }
    }
}

What I don't understand: Why are oldMatrix and newMatrix of size NI and not of size NJ ?

Upvotes: 0

Views: 106

Answers (2)

Cramer
Cramer

Reputation: 1795

int (*oldMatrix)[NJ] = new int[NI][NJ];

The [NJ] isn't declaring it's length there, but rather is part of its type declaration. oldMatrix is a pointer to arrays of length NJ, which is set to point to a dynamic array of length NI arrays.

It's equivalent to

typedef int row_type[NJ];
row_type *oldMatrix = new row_type[NI];

EDIT: Tested

Upvotes: 2

Prakash M
Prakash M

Reputation: 651

Because NI indicates no of rows and NJ indicates no of columns.

                  NJ
          a1 a2 a3 a4
 NI     b1 b2 b3 b4
          c1 c2 c4 c4
          d1 d2 d3 d4

Upvotes: 1

Related Questions