Nagraju Kasarla
Nagraju Kasarla

Reputation: 47

How to allocate the memory for matrices(2DArray) dynamically in which rows and columns are also allocated dynamically?

In my code, it only allocating memory for one matrix. When I try to allocate memory for two matrices here just two columns of memory are allocating and there is no other chance to allocate memory for the second matrix.

Here is my Code

    void 2DArray()
     {
         int noOfRows, noOfColumns, noOfMatrices;
         printf("\n\n ENTER THE NUMBER OF  MATRICES YOU WANT TO ADD : ");
         scanf("%d",&noOfMatrices);
         int **2DArray = (int**)malloc((noOfMatrices * sizeof(int)));

         for(int i = 0; i < noOfMatrices; i++)
          {
                  2DArray[i] = (int*)malloc((sizeof(int) * noOfRows));
          }
     }

Please help me!

Upvotes: 0

Views: 45

Answers (1)

0___________
0___________

Reputation: 67476

In C:

void *allocate2DintArray(size_t cols, size_t rows)
{
    int (*arr)[rows][cols];
    return malloc(sizeof(*arr));
}

In C++ (one of the possible ways)

vector <vector <int>> Matrix(rows, vector <int>(cols, 0));

Upvotes: 1

Related Questions