Array

Hello everyone, i just begun practice with arrays and i want to create a dynamic 2d array but my row and column size are limited by the initialized values for their respective variables. please help me make user be able to set rows and columns to any size preferred.


#include <iostream>
#include <iomanip>
using namespace std;

int main(){

int row=5, col=5;
int arrayTest[row][col];

//Setting rows and columns
cout<<"Set number of rows : "<<endl;
cin>>row;
cout<<"Set number of columns : "<<endl;
cin>>col;

//input elements
cout<<"Enter Elements "<<endl;
for(int i=0; i<row;i++){
for(int j=0; j<col; j++){
cin>> arrayTest[i][j];
}
}
system("cls");

//display elements
cout<<"Your Array is : "<<endl;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout<<" " << arrayTest[i][j]<<" ";
}
cout<<"\n";
}
system("pause");
return 0;
}]
Last edited on
You could use a vector of vectors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

int main(){

	int row=5, col=5;

	//Setting rows and columns
	cout<<"Set number of rows : "<<endl;
	cin>>row;
	cout<<"Set number of columns : "<<endl;
	cin>>col;
	
	vector<vector<int>> arrayTest(col, vector<int>(row));

	//input elements
	cout<<"Enter Elements "<<endl;
	for(int i=0; i<row;i++){
		for(int j=0; j<col; j++){
			cin>> arrayTest[i][j];
		}
	}
	system("cls");

	//display elements
	cout<<"Your Array is : "<<endl;
	for(int i=0; i<row; i++){
		for(int j=0; j<col; j++){
			cout<<" " << arrayTest[i][j]<<" ";
		}
		cout<<"\n";
	}
	system("pause");
	return 0;
}


http://www.cplusplus.com/reference/vector/vector/
You are also able to use a C++ dynamic array.
1
2
3
4
int* arr;
int size;
cin >> size;
arr = new int[size];

Just make sure to delete [] arr afterwards!

For two-dimensional dynamic arrays. Just make a pointer to an array of pointers.
1
2
3
4
5
6
7
int** arr2D;
int rowLen, colLen;
cin >> rowLen;
arr2d = new int*[rowLen];
cin >> colLen;
for (int i = 0; i < rowLen; i++)
     arr2D[i] = new int[colLen];

(Though honestly I prefer vectors usually.)
https://www.tutorialcup.com/cplusplus/dynamic-memory.htm Has a very good explanation.
Thank you Peter87, I am grateful. the truth is I have no idea about vectors so I will get on it and find out more. my observation though is, for a 1 column array, it seems not to respond. Perhaps you may know why or am not observing well. I will also like to add that your code works perfect. Thank you.
Last edited on
Looks like I have put row and col in the wrong order. To work correctly with your code it should be:

 
vector<vector<int>> arrayTest(row, vector<int>(col));
int * matrix = new int[rows*cols];

matrix[desired_row*cols+desired_col] = value; //access 1d as if 2d.

much easier to allocate, destroy, copy, reshape, save/load to file, print, and more.

delete is just
delete [] matrix;
Last edited on
Hello guys, I have tried the pointers method to dynamically allocate memory for the rows and columns of my array but there's nothing dynamic about the method that I can see. It only works if i initialize my row and column variables which becomes a limit for my array row and column size. please help me find what is wrong with my code.

//Using pointers
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main(){
int row=2, col=2;
int** arrayTest;
arrayTest = new int*[row];

for(int i=0; i!=row; ++i){
arrayTest[i]=new int[col];
}
//User specify dimension of Array
cout<<"Enter number of rows : "<<endl;
cin>>row;
cout<<"Enter number of columns : "<<endl;
cin>>col;
//Input elements
cout<<"Enter elements : "<<endl;
for(int i=0; i!=row; i++){
for(int j=0; j!=col; j++){
cin>>arrayTest[i][j];
}
}
//Display elements
cout<<"Your Array is : "<<endl;
for(int i=0; i!=row; i++){
for(int j=0; j!=col; j++){
cout<<" "<<arrayTest[i][j]<<" ";
}
cout<<"\n";
}
//Free memory
for(int i=0; i!=row; ++i){
delete[]arrayTest[i];
delete[]arrayTest;
}
return 0;
}
Hello Peter87, i have tried your new vector code but it still doesnt work when I set either row or column to 1. I think they both do similar jobs only either in rows or column. I tried using both simultaneously but I got a message it has been previously declared.
Thank you.

vector<vector<int>> arrayTest(col, vector<int>(row));

vector<vector<int>> arrayTest(row, vector<int>(col));
You are making the array when row and column are equal to two. Simply move arrTest = new int*[row]; and its corresponding for loop to after row and col have been inputted. That way the array will be created with the number of elements from the user.

P.S. Code tags are very helpful.
Last edited on
Intro to vectors: https://cal-linux.com/tutorials/vectors.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>

int main()
{
    std::cout << "number of rows? " ;
    std::size_t nrows ;
    std::cin >> nrows ;

    std::cout << "number of cols? " ;
    std::size_t ncols ;
    std::cin >> ncols ;

    std::vector<int> a_row(ncols) ; // each row has ncols values
    std::vector< std::vector<int> > arrayTest( nrows, a_row ) ; // array has nrows rows

    std::cout << "enter " << nrows*ncols << " values\n" ;
    // http://www.stroustrup.com/C++11FAQ.html#for
    for( std::vector<int>& row : arrayTest ) // for each row in the array
        for( int& num : row ) std::cin >> num ; // enter value for each number in the row

    std::cout << "your array is\n" ;
    for( const std::vector<int>& row : arrayTest ) // for each row in the array
    {
        for( int num : row ) std::cout << num  << ' ' ; // print each number in the row
        std::cout << '\n' ;
    }
}
closed account (E0p9LyTq)
Vectors are versatile:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <vector>
#include <numeric>

template<typename T>
void Print2DArray(std::vector<std::vector<T>> const&);

int main()
{
   // creating a sized vector
   std::vector<int> aVec(5);
   std::cout << aVec.size() << '\n';

   for (size_t itr = 0; itr < aVec.size(); itr++)
   {
      std::cout << aVec[itr] << ' ';
   }
   std::cout << "\n\n";

   // creating a sized vector filled with a value other than zero
   std::vector<int> aVec2(5, 100);
   std::cout << aVec2.size() << '\n';

   for (auto& itr : aVec2)
   {
      std::cout << itr << ' ';
   }
   std::cout << "\n\n";

   std::cout << "Creating a 2-dimensional vector, enter row size: ";
   int row_size;
   std::cin >> row_size;

   std::cout << "Enter column size: ";
   int col_size;
   std::cin >> col_size;

   std::cout << "\n";

   // create a 2 dimensional int vector with known dimensions
   std::vector<std::vector<int>> aVector(row_size, std::vector<int>(col_size));

   // initialize the vector with some values other than zero
   int start  = 101;
   int offset = 100;

   for (auto& itr : aVector)
   {
      std::iota(itr.begin(), itr.end(), start);
      start += offset;
   }

   // let's display the filled 2D vector
   Print2DArray(aVector);
}
template<typename T>
void Print2DArray(std::vector<std::vector<T>> const& aVec)
{
   for (const auto& row_itr : aVec)
   {
      for (const auto& col_itr : row_itr)
      {
         std::cout << col_itr << ' ';
      }
      std::cout << '\n';
   }
}

5
0 0 0 0 0

5
100 100 100 100 100

Creating a 2-dimensional vector, enter row size: 5
Enter column size: 7

101 102 103 104 105 106 107
201 202 203 204 205 206 207
301 302 303 304 305 306 307
401 402 403 404 405 406 407
501 502 503 504 505 506 507

3D vectors are doable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <vector>

int main()
{
   std::cout << "Creating a 3-dimensional vector, enter depth size: ";
   int depth_size;
   std::cin >> depth_size;

   std::cout << "Enter row size: ";
   int row_size;
   std::cin >> row_size;

   std::cout << "Enter column size: ";
   int col_size;
   std::cin >> col_size;

   std::cout << "\n";

   // create a 3 dimensional int vector with known dimensions
   std::vector<std::vector<std::vector<int>>> aVector(depth_size, std::vector<std::vector<int>>(row_size, std::vector<int>(col_size, 0)));

   // let's display the initial 3D vector
   for (int depth_loop = 0; depth_loop < depth_size; depth_loop++)
   {
      for (int row_loop = 0; row_loop < row_size; row_loop++)
      {
         for (int col_loop = 0; col_loop < col_size; col_loop++)
         {
            // let's display the filled 2D vector
            std::cout << aVector[depth_loop][row_loop][col_loop] << ' ';
         }
         std::cout << '\n';
      }
      std::cout << '\n';
   }
   std::cout << '\n';

   // initialize the vector with some values
   for (int depth_loop = 0; depth_loop < depth_size; depth_loop++)
   {
      for (int row_loop = 0; row_loop < row_size; row_loop++)
      {
         for (int col_loop = 0; col_loop < col_size; col_loop++)
         {
            aVector[depth_loop][row_loop][col_loop] = (((depth_loop + 1) * 100) + ((row_loop + 1) * 10) + col_loop + 1);
         }
      }
   }

   // let's display the filled 3D vector
   for (int depth_loop = 0; depth_loop < depth_size; depth_loop++)
   {
      for (int row_loop = 0; row_loop < row_size; row_loop++)
      {
         for (int col_loop = 0; col_loop < col_size; col_loop++)
         {
            // let's display the filled 2D vector
            std::cout << aVector[depth_loop][row_loop][col_loop] << ' ';
         }
         std::cout << '\n';
      }
      std::cout << '\n';
   }
}

Creating a 3-dimensional vector, enter depth size: 3
Enter row size: 4
Enter column size: 5

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0


111 112 113 114 115
121 122 123 124 125
131 132 133 134 135
141 142 143 144 145

211 212 213 214 215
221 222 223 224 225
231 232 233 234 235
241 242 243 244 245

311 312 313 314 315
321 322 323 324 325
331 332 333 334 335
341 342 343 344 345


Thank you guys! i am most grateful. I have tried most of the solutions you have for me but I must say for some I dont have any idea of procedures so I have to do some more reading to catch up. But you are really helping me make progress!

My next problem is how to align the elements of an array of varying elements lengths to their respective columns.
Last edited on
Just for fun here's a small example of using malloc() and realloc() to create and resize c-style arrays.
You wouldn't normally do this in an important program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <cstdlib>
using std::cin;
using std::cout;

// Create memory space for a (rows x cols) c-style array
int** createArray(int rows, int cols)
{
	int** array = (int**) malloc( rows*sizeof(int*) );
	for(int i = 0; i < rows; i++)
		*(array+i) = (int*) malloc( cols*sizeof(int) );
	return array;
}

// uses realloc() to dynamically resize the array. Returns
// a pointer to the newly created array
int** resizeArray(int rows, int cols, int** array)
{
	int** newarray = (int**) realloc( array, rows*sizeof(int*) );
	for(int i = 0; i < rows; i++)
		*(newarray+i) = (int*) realloc( *(newarray+i), cols*sizeof(int) );
	return newarray;
}

// Free memory 
void destroyArray(int rows, int cols, int** array)
{
	for(int i = 0; i < rows; i++)
		free( *(array + i) );
	free(array);
}

// Fill array with random ints
void stuffArray(int rows, int cols, int** array) {
	for(int i = 0; i < rows; i++)
		for(int j = 0; j < cols; j++)
			array[i][j] = rand() % 90 + 10; 
}

// Show it
void printArray(int rows, int cols, int** array) {
	for(int i = 0; i < rows; i++) {
		for(int j = 0; j < cols; j++)
			cout << array[i][j] << " ";
		cout << "\n";
	}
	cout << "\n\n";
}


int main()
{
	int rows, cols;
	cout << "What are the dimensions of your array : ";
	cin >> rows >> cols;

	int** myArray = createArray(rows, cols);
	stuffArray(rows, cols, myArray);
	printArray(rows, cols, myArray);

	cout << "Enter new dimensions for your array : ";
	cin >> rows >> cols;

	myArray = resizeArray(rows, cols, myArray);
	stuffArray(rows, cols, myArray);
	printArray(rows, cols, myArray);

	destroyArray(rows, cols, myArray);

	return 0;
}


whether using realloc or just copying the old buffer to a new one to resize or using a vector, resizing is slow and clunky (and doing the same thing pretty much in all these cases, though vectors try to overallocate to avoid it somewhat) and best avoided if at all possible.


I still recommend a linear block of memory. Its easier to deal with this when it happens; for simple types memcpy can get the aggravating movement over because its one block, and resize and delete etc are simplier than the looping mess of a 2-d construct --- across the board its the better way.

Thanks guys! Much appreciated.
Topic archived. No new replies allowed.