Monday, February 21, 2011

C - Sending the contents of a matrix in one function to a matrix in another function

Good evening.

How can I pass the contents of a char matrix in one function to another matrix of equal dimensions in another function?

Many thanks in advance.

From stackoverflow
  • Pass the pointer to the first element in the matrix, and the size.

  • Since you appear to know that the matrices are of constant size, the task is as simple as passing a double pointer (char** here) to the function, which refers to the matrix being passed.

    You will need to pass the dimensions if the rows/columns of the passed matrix is unknown, however, since C does not track the size of arrays in memory (they are no more than pointers with syntactic sugar).

    newacct : this assumes that his matrix is referred to as an array of pointers to arrays, while chances are he just has a regular contiguous 2-D array
  • You can copy the matrix contents the memcpy function.

    /*
    * mat: matrix to duplicate.
    * rows: rows in mat.
    * cols: cols in mat.
    */
    void matdup(char mat[][],size_t rows,size_t cols){
    
        char dupmat[rows][cols];//duplicate matrix in stack.
    
        memcpy((void*)dupmat,(void*)mat,rows*cols);
    
        //do stuff with matrix here.
    }
    

    With this, you can have a new matrix to use inside of the matdup function.

    Christoph : +1; there's no need to cast to `void *`, though

0 comments:

Post a Comment