Created a 3x2 matrix dynamically; printing it displays a 2x2 matrix - c++

I am getting issues. I want to create 2D array rows=3 cols=2
My code is as follows
int **ptr;
int row=3;
int col=2;
ptr=new int *[col];
for (int i=0;i<col;i++)
{
ptr[i]=new int [row];
}
for (int i=0;i<row;i++)
{
for (int j=0;j<col;j++)
{
cout<<ptr[i][j]<<" ";
}
cout<<endl;
}
But i am getting output (2*2)
0 0
0 0

When you work with 2D arrays you have the following:
HOLDS YOUR ROWS
|
|
[x0] ([x0_1][x0_2][x0_3]...[x0_n]) <- ROW ARRAY
[x1] ([x1_1][x1_2][x1_3]...[x1_n]) <- ROW ARRAY
[x2] ([x2_1][x2_2][x2_3]...[x2_n]) <- ROW ARRAY
. .
. .
. .
[xm] ([xm_1][xm_2][xm_3]...[xm_n]) <- ROW ARRAY
Which means that first you have to create each row:
for (int i=0;i<row;i++)
{
ptr[i]=new int[col]; // Each row has col number of cells
}
From the table at the beginning of my post this gets you every ([xP_1][xP_2][xP_3]...[xP_n]).
Next part of your code has to actually initialize the cells in each row so in your outer loop you have to iterate over your rows and then in the inner loop you have to iterate over you columns because each row has COL cells from ptr[i]=new int[COL];. So we get:
for (int i=0;i<row;i++)
{
for (int j=0;j<col;j++)
{
cout<<ptr[i][j]<<" ";
}
cout<<endl;
}
So at the end we have (I've replaced row with rows and col with cols in order to make things more readable for you...I hope :D):
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
int **ptr;
int rows = 3;
int cols = 2;
ptr = new int *[rows];
for (int row=0; row<rows; row++)
{
ptr[row]=new int [cols];
}
for(int row=0; row<rows; row++)
{
for(int col=0; col<cols; col++)
{
ptr[row][col] = 0;
cout << ptr[row][col] << " ";
}
cout << endl;
}
// Do something with the 2D array
// ...
// Delete all
for(int row = 0; row < rows; row++) delete[] ptr[row];
delete[] ptr;
return 0;
}
The output is:
0 0
0 0
0 0
Hope this helps. Also have in mind that you need to initialize your array's cells with some values. It's just not considered a good practice to leave it like you do - create and then simply go right to the displaying part without adding any values.

Related

How to add a new row everytime a user asks to?

My task is to create a function that adds a row to a 2d Array everytime that a user asks to. For simplicity, I have a default row value to start with and a column value that should be kept. This task can be referenced to a bookshelf. Once a certain amount of books or on that row of the bookshelf, then move to the next row and begin placing books there.
Additionally, how should I free the program once a new row is created?
I am a new programmer and do apologize if my question sounds dumb. Thanks in advance!
Attached is what I have so far.
#include <iostream>
#include <string>
using namespace std;
int **addRows(int row, int cols, int values)
{
// Declare a 2d Array
int **twoD;
twoD = new int *[row];
// Fill each row with a column
for (int i = 0; i < row; i++)
{
twoD[i] = new int[cols];
}
// Fill each row, column with value
for (int i = 0; i < row; i++)
{
for (int j = 0; j < cols; j++)
{
twoD[i][j] = values;
}
}
// Return the 2d array
return twoD;
}
int main()
{
int **twoD;
int row = 1;
int cols = 5;
int values = 1;
int userInput;
// Call the function with 3 parameters by assigning the returned array to twoD
twoD = addRows(row, cols, values);
cout << "Do you want to add a row? 1 for yes, 0 for no, -1 to exit";
cin >> userInput;
while (userInput != -1)
{
if (userInput == 1)
{
twoD = addRows(row, cols, values);
}
else
{
// Print out each value in the 2d Array to console
for (int i = 0; i < row; i++)
{
for (int j = 0; j < cols; j++)
{
cout << twoD[i][j];
}
cout << endl;
}
// Free the memory
for (int i = 0; i < row; i++)
{
delete (twoD[i]);
}
delete (twoD);
}
cout << "Do you want to add a row? 1 for yes, 0 for no, -1 to exit";
cin >> userInput;
}
}
Your code is missing the following lines:
//remove memory allocation of array of columns for each row
for (int i = 0; i < row; i++) {
delete[] twoD[i];
}
//remove memory allocation of array of rows
delete[] twoD;
//increase the amount of rows in our new twoD matrix
row++;
in this section:
if (userInput == 1)
{
//right here
twoD = addRows(row, cols, values); //call addRows to generate the new twoD matrix with the increased row count
}

Passing dynamically allocated 2D char array causes segmentation error?

I am having trouble using a function.
I have two functions.
createTwoDArray: prompts user for row and column sizes, creates a new 2D array and returns it while also modifying the row and column variables passed to it.
printTwoDArray: should take in a 2d array and print everything. However, when calling this function, segmentation fault occurs immediately. Not one line of code inside the function is called even.
Thank you :)
int column, row;
char** createTwoDArray(int& column, int& row) {
int min, max, i, j;
cout << "\nPlease enter row size:";
cin >> i;
row = i;
cout << "\nPlease enter column size:";
cin >> j;
column = j;
char** dynamicArray2 = new char*[column];
for(i = 0; i < row; i++) {
dynamicArray2[i] = new char[column];
for(j = 0; j < column; j++) {
dynamicArray2[i][j] = '\0';
}
}
return dynamicArray2;
}
void printTwoDArray(char** array, int row, int column) {
//
}
//
char** array2 = new createTwoDArray(column, row)
printTwoDArray(array2, column, row); //this causes the segmentation error
//
There are two errors: 'column' was used to allocate rows, and row and column were mixed up when calling printTwoDArray().
Here is the fixed code. It runs fine in Visual C++.
#include "pch.h"
#include <iostream>
int column, row;
char** createTwoDArray(int& column, int& row) {
int min, max, i, j;
std::cout << "\nPlease enter row size:";
std::cin >> i;
row = i;
std::cout << "\nPlease enter column size:";
std::cin >> j;
column = j;
// *** Use row, not column to allocate the number of rows.
char** dynamicArray2 = new char*[row];
for (i = 0; i < row; i++) {
dynamicArray2[i] = new char[column];
for (j = 0; j < column; j++) {
dynamicArray2[i][j] = '\0';
}
}
return dynamicArray2;
}
void printTwoDArray(char** array, int row, int column) {
printf("\nPrinting %d rows:\n\n", row);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
printf(" %2d", array[i][j]);
}
printf("\n");
}
}
int main()
{
//
char** array2 = createTwoDArray(column, row);
// Pass row and column in the right order!
printTwoDArray(array2, row, column);
//
return 0;
}

2D C++ Grid display

Hi guys I have a 2D array of char '-' in it and I want to print it out.
However I want to print it in a grid format so that the point (0,0) is on the bottom left of the array not the top left.
For example now it's printing:
0 1 2 3
1
2
3
and I want it to print in the way:
3
2
1
0 1 2 3
How can I print my array in order to act more like a graph than an array?
Thanks.
EDIT: This is what my printing function looks like
displayGrid(){
for(int column = 0; column<gridSize; column++){
for(int row = 0; row < gridSize; row++){
std::cout<<gridArray[row][column]<< " ";
}
std::cout<<std::endl;
}
}
This is how I fill the elements in my array:
createGrid(){
int gridSize = 50;
for(int column = 0; column<gridSize; column++){
for(int row=0; row<gridSize; row++){
gridArray[row][column] = empty;
}
}
//gridArray[0][1] = full; first value is x, second is y. Works.
}
Just let your first loop start at gridSize and decrement it.
Should look similar to this:
displayGrid(){
for(int column = gridSize; column>=0; column--){
for(int row = 0; row < gridSize; row++){
std::cout<<gridArray[row][column]<< " ";
}
std::cout<<std::endl;
}
}

Multi-Dimensional Array sorting in c++

I am using sort() function for single array it works well.
I also used this for multi-dimensional array but this is not work.
Here is code:
#include <iostream>
using namespace std;
int main(){
int a[2][3];
a[0][1]=7;
a[1][0]=1;
a[1][1]=3;
sort(a,a+3);
cout<<a[0][1]<<"\t"<<a[1][0]<<"\t"<<a[1][1];
return 0;
}
I know I use single array for these value but this is example and I want it in multi-dimensional array.
Using your code just use std::sort on each row of the multidimensional array. ie.
#include <iostream>
using namespace std;
int main(){
int a[2][3];
a[0][0]=1;
a[0][1]=7;
a[0][2]=3;
a[1][0]=6;
a[1][1]=2;
a[1][2]=5;
for(int i = 0; i < 2; i++) {
sort(a[i],a[i]+3);
}
for(int row = 0; row < 2; row++) {
for(int col = 0; col < 2; col++) {
cout << a[row][col] << " ";
}
}
return 0;
}
I initiated every element of your multidimensional array a, since your declared a to be size 6 (2 rows, 3 columns). This would output 1 3 7 2 5 6, because it sorts the rows from least to greatest. If you wanted to sort the multidimensional array so that the output would read 1 2 3 5 6 7 then you would need to do something like this:
#include <iostream>
using namespace std;
int main(){
int a[2][3];
int b[6];
int count = 0;
a[0][0]=1;
a[0][1]=7;
a[0][2]=3;
a[1][0]=6;
a[1][1]=2;
a[1][2]=5;
for(int row = 0; row < 2; row++) {
for(int col = 0; col < 3; col++) {
b[count] = a[row][col];
count++;
}
}
sort(b, b+6);
count = 0;
for(int row = 0; row < 2; row++) {
for(int col = 0; col < 3; col++) {
a[row][col] = b[count];
count++;
}
}
for(int row = 0; row < 2; row++) {
for(int col = 0; col < 3; col++) {
cout << a[row][col] << " ";
}
}
return 0;
}
This second example is probably the worst possible way to go about sorting a multidimensional array though. Let me know if you find an error in my code, I was unable to test, or need additional help.
As the multidimensional arrays are contiguous you can also try:
int main()
{
int a[2][3];
a[0][0]=1;
a[0][1]=7;
a[0][2]=3;
a[1][0]=6;
a[1][1]=2;
a[1][2]=5;
std::sort(&a[0][0], &a[1][3]);
for(int row = 0; row < 2; row++) {
for(int col = 0; col < 3; col++) {
std::cout << a[row][col] << " ";
}
}
}
Depending on what you want. It is also possible to write a begin() and end() for multidimensional arrays.

How to set according to the x-axis Symmetry of Matrix

I need a function that can take to according to the x-axis of symmetry of the matrix.
input (matrix[i][j]):
1 2 3
4 5 6
7 8 9
output (matrix[i][j]):
7 8 9
4 5 6
1 2 3
How can i do this on the same matrix?
How should I write the inverse function?
void inverse(.......)
{
..
..
..
}
int main(){
int **matrix, i, j, k, row, column;
cout << "Row and column:" ;
cin >> row >> column;
matrix = new int*[row];
for (i=0; i<row; ++i){
matrix[i] = new int[column];
}
cout << "input elements of matrix: " << endl;
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cin >> *(*(matrix+i)+j);
}
}
inverse (........);
for(i=0; i<row; i++){
for (j=0; j<column; j++){
cout << *(*(matrix+i)+j);
}
cout << endl;
}
return 0;
}
In this particular case, you can modify the loop to print the matrix backwards:
for(i = 0; i < row; i++) {
->
for(i = row - 1; i >= 0; i--) {
But if you want to actually do something to the data, my suggestion would be to refactor this code to use std::vector.
std::vector<std::vector<int> > matrix(numberOfRows, std::vector<int>(numberOfColumns));
// You can use std::vector<std::valarray<int> > matrix; alternatively.
You would then flip it simply by using an STL function:
std::reverse(matrix.begin(), matrix.end());
Edit:
Well, if you don't want to use std::vector for the time being and for this particular case, what you would do is this:
void flipMatrix(int** matrix, int rows, int columns) {
int middle = rows/2; // I expect it to truncate for an odd number of rows.
// Temporary row for swapping
int* tempRow;
for (int i = 0; i < middle; i++) {
// swap rows
tempRow = matrix[i];
matrix[i] = matrix[rows - i - 1];
matrix[rows - i - 1] = tempRow;
}
}