Shreyas Muralidharan
Shreyas Muralidharan

Reputation: 11

Filling C array with pointers

The following function is supposed to fill a two dimensional array with floats increasing by 0.5

void MatrixFill(float *pf, float x, int rows, int columns, FILE *fp) {
    int i, j;
    printf ("\n***\tBegin MatrixFill\t***\n\n");
    fprintf (fp, "\n***\tBegin MatrixFill\t***\n\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
          *(pf + i + columns ) = x;
          x += 0.5;
        }
    }    
    printf ("\n***\tEnd MatrixFill\t***\n\n");
    fprintf (fp, "\n***\tEnd MatrixFill\t***\n\n");
}

However, I'm not sure what goes in my "filling statement." (*(pf+stuff)=x;)

Any help with pointers/ array filling would be great. Thanks!

Upvotes: 1

Views: 104

Answers (1)

ThunderWiring
ThunderWiring

Reputation: 738

this is were you got the mess: (pf + i + columns ) = x it should be: *(pf + i + j * rows)

Why is that?

First, you must see that each row passes through all the columns:

     col1|col2|col3
     ----+----+----
row1     |    |
     ----+----+----

Now, you see if you want to get to row number x, you must pass through all the columns x times!

Generally Speaking

in each 2D array arr[COLS][ROWS] where COLS and ROWS are the total numbers of columns and rows consequently, arr[i][j] = arr[i + j * COLS] = arr[j + i * ROWS]

Upvotes: 1

Related Questions