Hannes Hultergård
Hannes Hultergård

Reputation: 1207

Convert array to matrix in C

I have a homework where i have to convert an array to a matrix. I already have a working solution, however since I didn't use the size parameter I removed it from the function declaration (and the tests), but my teacher did not like that. So now I would need help to figure out how size is supposed to be used here.

My function (with all parameters) looks like this:

static void array_to_matrix(int n_rows, int n_cols, cell_t matrix[][n_cols], const cell_t arr[], int size) {
    int i = 0;
    for (int r = 0; r < n_rows; r++) {
        for (int c = 0; c < n_cols; c++) {
            matrix[r][c] = arr[i++];
        }
    }
}

And the tests that my teacher has made looks like this:

#define ARR_EQUALS(v1, v2) printf( memcmp(v1, v2, sizeof(v1)) == 0 ? "true\n" : "false\n")

...

void test_array_to_matrix() {
    cell_t cells1[4];
    get_cells(cells1, 4, 0.5);
    cell_t world1[2][2];
    array_to_matrix(2, 2, world1, cells1, 4);

    int expected1[] = {1, 1};
    ARR_EQUALS(world1[0], expected1); // First row


    // Test a bigger one
    cell_t cells2[9];
    get_cells(cells2, 9, 0.5);
    cell_t world2[3][3];
    array_to_matrix(3, 3, world2, cells2, 9);
    int expected3[] = {1, 1, 0};
    ARR_EQUALS(world2[1], expected3); // Mid row
}

Upvotes: 0

Views: 197

Answers (1)

Sajib
Sajib

Reputation: 414

If it is guaranteed that size will be equal to n_rows*n_cols, then the size parameter is not used logically as it behaves just as a derived variable. However, your teacher most probably will not want to modify his/her tests code just to test your solution, that's why you have to follow the declaration he/she has given you which includes the size parameter. The test code knows that it will call array_to_matrix(int n_rows, int n_cols, cell_t matrix[][n_cols], const cell_t arr[], int size). But if you change it, then the existing test code will not work and will need to modify.

What we learn from here is that, we have to work in a team. Just because you can omit something, you shouldn't do it because you already agreed on an API declaration that is going to be used by others. Imaging joining a server team and you suddenly change the definition of an API, thousands of clients are going to suffer for it.

Upvotes: 2

Related Questions