Sunday, February 19, 2023

How to return a 2-Dimensional array in C using a pointer

here's an example of a C function that performs matrix calculation and returns the result as a pointer to a separate function:
  


#include 
#include 

// Function to perform matrix multiplication
double* matrix_multiply(double* matrix1, double* matrix2, int rows1, int cols1, int cols2) {
    double* result = (double*)malloc(rows1 * cols2 * sizeof(double)); // Allocate memory for the result matrix
    int i, j, k;
    for (i = 0; i < rows1; i++) {
        for (j = 0; j < cols2; j++) {
            result[i*cols2+j] = 0; // Initialize the result element to 0
            for (k = 0; k < cols1; k++) {
                result[i*cols2+j] += matrix1[i*cols1+k] * matrix2[k*cols2+j]; // Perform matrix multiplication
            }
        }
    }
    return result; // Return the pointer to the result matrix
}

int main() {
    double matrix1[2][3] = {{1, 2, 3}, {4, 5, 6}}; // Define the first matrix
    double matrix2[3][2] = {{1, 2}, {3, 4}, {5, 6}}; // Define the second matrix
    int rows1 = 2, cols1 = 3, cols2 = 2; // Define the dimensions of the matrices

    // Call the matrix_multiply function and store the result in a pointer
    double* result = matrix_multiply(&matrix1[0][0], &matrix2[0][0], rows1, cols1, cols2);

    // Print the result matrix
    int i, j;
    for (i = 0; i < rows1; i++) {
        for (j = 0; j < cols2; j++) {
            printf("%.2f ", result[i*cols2+j]);
        }
        printf("\n");
    }

    free(result); // Free the memory allocated for the result matrix

    return 0;
}


  
In this example, the matrix_multiply function takes in two matrices (matrix1 and matrix2) and their dimensions (rows1, cols1, and cols2) as parameters. It allocates memory for the result matrix, performs the matrix multiplication, and returns the pointer to the result matrix. The main function defines two example matrices, calls matrix_multiply with these matrices and their dimensions, stores the pointer to the result matrix in a variable, and then prints the result matrix. Finally, it frees the memory allocated for the result matrix using the free function.

No comments:

Post a Comment