Answers for "return 2d array in c"

C++
1

print 2d array in c

// most of the time I forget that there should be matrix[i][j], not matrix[i]
#include <stdio.h>
// Abdullah Miraz
int main(){
    int i, j;

    int matrix[2][3] = {{2,3,4,5}, {7,8,9,1}};
    for(i=0;i< 2 ; i++){
        for(j=0;j<3;j++){
            printf("%d ", matrix[i][j]);
        }
    }
}
Posted by: Guest on July-30-2021
1

how to return 2d array from function c++

#include <cstdio>

    // Returns a pointer to a newly created 2d array the array2D has size [height x width]

    int** create2DArray(unsigned height, unsigned width)
    {
      int** array2D = 0;
      array2D = new int*[height];
    
      for (int h = 0; h < height; h++)
      {
            array2D[h] = new int[width];
    
            for (int w = 0; w < width; w++)
            {
                  // fill in some initial values
                  // (filling in zeros would be more logic, but this is just for the example)
                  array2D[h][w] = w + width * h;
            }
      }
    
      return array2D;
    }
    
    int main()
    {
      printf("Creating a 2D array2Dn");
      printf("n");
    
      int height = 15;
      int width = 10;
      int** my2DArray = create2DArray(height, width);
      printf("Array sized [%i,%i] created.nn", height, width);
    
      // print contents of the array2D
      printf("Array contents: n");
    
      for (int h = 0; h < height; h++)
      {
            for (int w = 0; w < width; w++)
            {
                  printf("%i,", my2DArray[h][w]);
            }
            printf("n");
      }
    
          // important: clean up memory
          printf("n");
          printf("Cleaning up memory...n");
          for (int h = 0; h < height; h++) // loop variable wasn't declared
          {
            delete [] my2DArray[h];
          }
          delete [] my2DArray;
          my2DArray = 0;
          printf("Ready.n");
    
      return 0;
    }
Posted by: Guest on June-03-2021
0

how to get input in 2d array in c

#include <stdio.h>

int main(){

    printf("Enter the number of columns");
    int i; 
    scanf("%d", &i);
    printf("Enter the number of rows");
    int y; 
    scanf("%d", &y);

    int r[i][y];
    int a;
    int b;

        for (a=0; a<i; a++){
            for (b=0; b<y; b++){
    scanf("%d",&r[a][b]);
        }
    }
}
Posted by: Guest on November-19-2020

Browse Popular Code Answers by Language