Question about the last two parameters in C


  • 0
    H

    Dears,

    I have a question about the method signature of C:

    int** generate(int numRows, int** columnSizes, int* returnSize)
    

    Q1: The second parameter stores the number of columns in each row, is that right?
    If so, why should it be two-dimensional instead of one-dimensional?
    I think that one-dimension is enough?

    Q2: As for the third parameter, it simply stores the number of rows, which is exactly the same as the first parameter. Then, why we need the value that seems like a duplicated information?

    Thanks for your time and it would be grate to hear from you.


  • 4

    Q1: Yes. This is because the pointer int * is passed in using a pointer int ** so it allows you to allocate a 1D array like this in your function:

    *columnSizes = (int *) malloc(sizeof(int) * col_size);
    

    If columnSizes was passed in using int *, then if you attempt to assign the reference to 1D array like this:

    columnSizes = (int *) malloc(sizeof(int) * col_size);
    

    You are assigning the reference to the copy of the pointer being passed in, and therefore the caller won't know about the 1D array you allocated.

    Q2: Yes for this question it is duplicated information. This is due to the design such that it is generic and work for all other cases. I will work on removing this duplicate parameter. Thanks for pointing it out.


    UPDATE:
    I have removed the duplicate third parameter. Please click the refresh button just above the code editor to get the updated default code definition.


Log in to reply
 

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