Max
Max

Reputation: 45

Dynamic 2D array without using new

I've been posed with creating a dynamic 2D array in C++ without using new in C++. I have been trying for a while to make something work but I'm clueless as to what I'm supposed to do.

Edit: Sorry, should have been more specific. Just to be transparent, yes it is homework, and no I don't want it solved I just want to be pointed (no pun intended) in the right direction to code it myself.

The order, for reference, is as follow: Develop a console application to create a type int matrix of size m x n using pointers. The user must input the values for the size of the matrix from the keyboard and its contents must be randomly generated (1 - 100). Then, the transpose of the matrix must be calculated and shown (it's necessary to create classes).

We can't use new, nor vector, as we have to do it just via pointers with uni-dimensional arrays. So far I created a class that represent the "rows", and another class which represents the "columns". The columns go into the rows and the rows go into another class called matrix. That was the idea but was having trouble implementing it.

Upvotes: 0

Views: 358

Answers (2)

Max
Max

Reputation: 45

malloc did the trick. Here is the code I used to test it. It was a bit convoluted to figure out how to write the matrix loop but once I got it down I realized how obvious it was.

Matriz::Matriz(int numFil, int numCol)
    :numFil(numFil), numCol(numCol)
{
    mat = (int *)malloc(numFil * numCol * sizeof (int));

    int c = 0;

    for(int i = 0; i < numFil; i++)
    {
        for(int j = 0; j < numCol; j++)
        {
            *(mat + i * numCol + j) = ++c;
        }
    }
}

void Matriz::printMat()
{
    for(int i = 0; i < numFil; i++)
    {
        for(int j = 0; j < numCol; j++)
        {
            std::cout << *(mat + i*numCol + j);
        }
         std::cout << std::endl;
    }
}

Upvotes: 2

eerorika
eerorika

Reputation: 238351

new is the only way to create dynamic objects or arrays in standard C++. So, depending on how you interpret the task, it could be considered impossible.

If we assume that it is OK for you to call a standard function that internally calls new, then the problem is solvable. A commonly used way to create a dynamic array in C++ is to use std::vector. Elements of std::vector may not be arrays however, so a 2D dynamic array is not technically possible using it. One workaround is to wrap the array within a class, and use the class as element of the vector. There is a standard template for such array wrapper: std::array. An example of a vector of array wrappers:

std::vector<std::array<type_of_element, 10>> name_of_vector(number_of_arrays);

The elements of the arrays within the dynamic array managed by the vector will have effectively the same layout as a 2D array would.

Upvotes: 4

Related Questions