Sunday, February 19, 2023

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

In C, it is not possible to return a 2-D array directly. However, we can return a struct that contains a 2-D array. Here's an example function that creates a 2-D array of integers and returns it as part of a struct:
  


#include 

struct Array2D {
  int array[3][3];
};

struct Array2D matrixMultiplication(struct Array2D a, struct Array2D b) {
    
  struct Array2D result  {0};
  int i, j, k;

  for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {
      result.array[i][j] = 0;
      for (k = 0; k < 3; k++) {
        result.array[i][j] += a.array[i][k] * b.array[k][j];
      }
    }
  }

  return result;
}

int main() {
  struct Array2D a = {
    {{1, 2, 3},
     {4, 5, 6},
     {7, 8, 9}}
  };

  struct Array2D b = {
    {{9, 8, 7},
     {6, 5, 4},
     {3, 2, 1}}
  };

  struct Array2D c = matrixMultiplication(a, b);

  // Print the result
  printf("Result of matrix multiplication:\n");
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      printf("%d ", c.array[i][j]);
    }
    printf("\n");
  }

  return 0;
}



  
We could also write similar function which return a pointer instead of structure See this post

No comments:

Post a Comment