Search code examples
cmatrixdynamic-arrays

Ways to create dynamic matrix in C?


This is the only way I know to create a matrix (2D array) in C, dynamically, and reading user input into its elements:

  • Creating a pointer to an array of x pointers, where each pointer represents a line in the matrix - x is the number of lines in the matrix (its height).

  • Pointing each pointer in this array to an array with y elements, where y is the number of columns in the matrix (the width).


int main()
{

  int i, j, lines, columns, **intMatrix;

  printf("Type the matrix lines:\t");
  scanf("%d", &lines);
  printf("Type the matrix columns:\t");
  scanf("%d", &columns);

  intMatrix = (int **)malloc(lines * sizeof(int *)); 
  //pointer to an array of [lines] pointers

  for (i = 0; i < lines; ++i)
      intMatrix[i] = (int *)malloc(columns * sizeof(int)); 
      //pointer to a single array with [columns] integers

  for (i = 0; i < lines; ++i)
  {
      for (j = 0; j < columns; ++j)
      {
        printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
        scanf("%d", &intMatrix[i][j]);
      }
  }

Are there other ways to do this?


Solution

  • You can try like this

    int main()
    {    
      int i, j, lines, columns, *intMatrix;
    
      printf("Type the matrix lines:\t");
      scanf("%d", &lines);
      printf("Type the matrix columns:\t");
      scanf("%d", &columns);
    
      intMatrix = (int *)malloc(lines * columns * sizeof(int)); 
    
      for (i = 0; i < lines; ++i)
      {
          for (j = 0; j < columns; ++j)
          {
            printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
            scanf("%d", &intMatrix[i*lines + j]);
          }
      }