-2

I don't understand what x[i][j] = -i*cols - j ; is exactly doing.. Can someone explain because i am beginner. I cant understand pointers '*'. Sorry for bad English.

int main(int argc, char *argv[]) { 
    int a[5][5]; 
    readarray(5, 5, a); 
    printarray(3, 5, a); 
    return 0; 
}

void readarray(int rows, int cols, int x[rows][cols]) { 
    int i, j; 

    for (i = 0; i< rows; i++) 
        for (j = 0; j < cols; j++) 
            x[i][j] = -i*cols - j ; 
}

void printarray(int rows, int cols, int x[rows][cols]) { 
    int i, j; 
    for (i = 0; i< rows; i++) { 
        for (j = 0; j < cols; j++) 
            printf("%4d", x[i][j]) ; 
        printf("\n"); 
    } 
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • 2
    `i` is negated then multiplied by cols then j is subtracted from that. This result is then stored in the 2 dimensional array using i and j as the indices – Lee Taylor Apr 28 '14 at 16:09

3 Answers3

4

* here is for the multiplication, not pointers.

x[i][j] = -i*cols - j ;

There are several things happen here:

  1. negative: -i
  2. multiplication: (-i) * cols
  3. substraction: - j
  4. assignment: assign the result of the right side to x[i][j].

Check out this thread if you want to know the difference between using * for dereference and multiplication.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

That is just populating the values of the array elements.

x[i][j] = -i*cols - j ; = x[i][j] = -i*5 - j ;

x[0][0] = 0
x[0][1] = -0*5 - 1 = -1
. . .
x[1][0] = -1*5 - 0 = -5
. . 
x[3][3] = -3*5 - 3 = -18

and so on..

brokenfoot
  • 11,083
  • 10
  • 59
  • 80
0

I think only one multiplication is being performed. No pointers are being used.

i=2;
j=5;
cols = 5;

x[2][5] = -2 * 5 - 5
Hugo Pedrosa
  • 347
  • 2
  • 12