2D Arrays

I have a 2d array and I created it with pointers.

int **array;
array = new int* [size];

for (int i = 0; i < size; i++)
array[i] = new int [K];

for (int i = 0; i < size; i++){
delete [] array[i];
}
delete [] array;
}

But what I want is to store values in my 2D array that has rows with different number of elements. That is,

1 0 0 1
1 0 1
2 1
1 3 4

and so on. It should probably be dynamic so I should be able to add more rows whenever I want.

Thanks-

So the K in your case has to be 4 for the first row, 3 for the second, 2 for the third, 3 for the fourth. There shouldn't be a problem with that.

It should probably be dynamic so I should be able to add more rows whenever I want.

This is achieved by using vectors, e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
int main()
{
    std::vector< std::vector<int> > array =
    {{1, 0, 0, 1},
     {1, 0, 1},
     {2, 1},
     {1, 3, 4}};

    // can add rows whenever
    std::vector<int> row = {1,2,3,4,5};
    array.push_back(row);

    // can resize existing rows, too
    array[0].resize(6);

    // print:
    for(auto& row: array) {
        for(int n: row)
            std::cout << n << ' ';
        std::cout << '\n';
    }
}

live demo: http://ideone.com/nYuW3Q
I don't understand the case with K. K will be fixed, such as K=5. How can it be 4, 3, 2, and 3? Also, is adding process possible with arrays and pointers?
if K is always 5 then all your row arrays have the same lengths. If you want them to have different lengths, then K would need to change. At what point in your program do you learn that the first row needs to have the length 4? That's the point where you can set K to 4 and create that row.
Okay, it makes sense. it shouldn't be fixed. Then, how can I change that K values for each row? Do I need to add some more lines to my code?
To add new rows, can following set of lines be added before deleting the array?

int* addedRow;
addedRow = new int [size];
Hi again!

For the "std::vector" code:

#include <iostream>
#include <vector>
int main()
{
std::vector< std::vector<int> > array =
{{1, 0, 0, 1},
{1, 0, 1},
{2, 1},
{1, 3, 4}};

// can add rows whenever
std::vector<int> row = {1,2,3,4,5};
array.push_back(row);

// can resize existing rows, too
array[0].resize(6);

// print:
for(auto& row: array) {
for(int n: row)
std::cout << n << ' ';
std::cout << '\n';
}
}

I receive some error messages: array must be initialized by constructor, not by {...}. and some more... How can they be fixed?


Last edited on
array must be initialized by constructor, not by {...}

Sounds like an old (pre C++11) compiler.
How can they be fixed?

Upgrade is most practical fix. Or you could rewrite that program using 1998 C++, something like
1
2
3
4
std::vector< std::vector<int> > array;
std::vector<int> r(4);
r[0] = 1; r[3] = 1;
array.push_back(r);
or any of the other ways to initialize a vector
Topic archived. No new replies allowed.