A pain for c programmer


  • 0
    V

    There are a few things not good for a c programmer.

    1. Frist, there is no need to return columnSizes, because the return data is a triangle, so the column size of each row equals the the row number, it is determined, there is no such a need to allocate memory and fill in the numbers 1, 2, 3, 4, ...

    2. The comments describe "assume caller free the memory", this is very wrong. Caller never know how callee allocates the memory, how can it free the memory? The right approach should be asking for user to write a function which caller can call for freeing the memory being allocated by user.

    In this particular problem, the total element of the triangle is n * (n + 1) / 2. I like to allocate one buffer outside of loop by using one malloc, and reference to the different location of this buffer for each row of the array. pseudo code:

    p = malloc(numRows * sizeof(int *)); // array
    buff = malloc(numRows * (numRows + 1) / 2 * sizeof(int)); // all element
    //assert(p && buff);
    for (i = 1; i <= numRows; i ++) {
    p[i - 1] = buff;
    ....
    buff += i;
    }

    when freeing the memory, it will be:

    free(p[0]);
    free(p);


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.