Dynamic matrix allocation in C++

Asked

Viewed 2,074 times

2

I would like to dynamically allocate this matrix in C++:

int main()
{
    int n,m;
    cin>>n>>m;


   if(n>m){cedula tabela[n][n];}
   else {cedula tabela[m][m];} return 0;}

but the code does not compile, I think it has to do with dynamic allocation, I tried to do the following:

int main()
{
    int n,m;
    cin>>n>>m;


   if(n>m){cedula* tabela= new cedula[n][n];}
   else {cedula* tabela = new cedula[m][m];} return 0;}

But you still haven’t compiled.

  • Do you want to do it in real C++ or just use C++ to program in C?

2 answers

2


-3

Study this artifact I created long ago and remove from it any concept that suits you.

#include <windows.h>
#include <stdio.h>
#include <psapi.h>
#include <time.h>
#include <string>

#define random_enveloped(min, max) ((rand() % (int) ((max + 1) - min)) + min)

using namespace std;

int main() {
    //HANDLE hProcess;
    //PROCESS_MEMORY_COUNTERS pmc;
    //hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId());

    int rows = 10;
    int cols = 10;

    int** matrix = (int**) malloc(rows * sizeof(int**));
    if(matrix == NULL)
    {
        printf("Erro...\n");
        exit(-1);
    }
    memset(matrix, 0, rows * sizeof(int**));

    for(int i = 0; i < rows; i++)
    {
        int* matrix_line = (int*) malloc(cols * sizeof(int*));
        if(matrix_line == NULL)
        {
            printf("Erro...\n");
            exit(-1);
        }
        memset(matrix_line, 0, cols * sizeof(int*));

        for(int j = 0; j < cols; j++)
        {
            matrix_line[j] = 2 * random_enveloped(1, 10);
        }

        matrix[i] = matrix_line;
    }

    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            printf("%02d ", matrix[i][j]);
        }

        printf("\n");
    }

    //printf("\n%lu\n", (pmc.WorkingSetSize / 1024) / 1024);

    //CloseHandle(hProcess);
}



His exit is something like the result below:

04 16 10 02 20 10 18 18 06 10
12 12 04 16 04 04 12 06 16 14
04 10 06 08 06 06 04 14 18 12
16 14 04 18 20 06 16 20 12 10
08 04 06 08 08 10 04 04 08 18
16 10 06 16 16 20 08 04 20 18
14 12 02 06 18 14 02 06 10 18
14 12 02 20 02 02 14 04 08 18
20 08 10 10 14 02 14 14 04 18
10 20 14 08 16 18 18 06 20 04



I hope it helps!

  • Hello! Could explain how the above code could be useful for doubt?

  • Shows dynamic allocation of matrices, which was the main question of the colleague.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.