0

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!

Suman Bhadra
  • 25
  • 1
  • 4
  • 1
    It is not 2D array. It is array of pointers!! – 0___________ Apr 25 '21 at 08:06
  • @Nagrocks Naa - `noOfRows` and `noOfColumns` are uninitialized - you have to make up your mind where their values shall come from. – Armali Apr 25 '21 at 08:09
  • Why are you tagging with C and C++? They are two completely different languages. – Jose Apr 25 '21 at 08:18
  • Please start with the [tour] and read [ask]. Also, describe your actual problems (observations, expectations etc.). Lastly, as mentioned above, go through the description of the tags that you applied, the two are mutually exclusive in general. – Ulrich Eckhardt Apr 25 '21 at 08:38

1 Answers1

1

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));
0___________
  • 60,014
  • 4
  • 34
  • 74
  • There is a debate if `sizeof(*arr)` is UB or not. See https://stackoverflow.com/questions/32985424/is-the-operand-of-sizeof-evaluated-with-a-vla?noredirect=1&lq=1 – tstanisl Apr 28 '21 at 08:56
  • @tstanisl all known by compilers do it properly - it means that their developers interpret it the different way than SO gurus. For me, compiler developers interpretation is more important than the SO one. – 0___________ Apr 28 '21 at 10:51