Array counting 858993460 in each slot - c++

I'm trying to create a two dimensional array, which I can use as coordinates for a map to be displayed. For the moment I'm just trying to get a character to display on screen over and over to create an effect in a box with the dimensions of the array. But at each coordinate it just displays some long number (maybe like the slots are empty or something?)
I feel like it might be a loss of data from the class member to the main function, but I'm really just guessing.
For example, I'm looking for an output something like this:
11111
11111
11111
11111
Source code:
#include <iostream>
using namespace std;
class Map_Blocks
{
public:
int Map_Width = 60;
int Map_Height = 15;
int Map_Array [15][60];
int Generate();
int Display();
};
int Map_Blocks::Generate()
{
int x, y;
for(y=0;y<Map_Height;y++)
{
for(x=0;y<Map_Width;x++)
{
Map_Array[y][x]=1;
}
}
return 0;
}
int Map_Blocks::Display()
{
int x, y;
for(y=0;y<Map_Height;y++)
{
for(x=0;y<Map_Width;x++)
{
cout<<Map_Array[y][x];
}
cout<<endl;
}
return 0;
}
int main(void)
{
Map_Blocks Size;
cout<<"Map Width ="<<Size.Map_Width<<endl;
cout<<"Map Height ="<<Size.Map_Height<<endl;
Map_Blocks disp;
disp.Display();
return 0;
}

You never call Generate() to initialize the array's content.
Add:
disp.Generate();
before the call to Display().

Related

Understand pointers

#include <iostream>
using namespace std;
class idk{
public:
int x;
int y;
};
void obj(idk* obj[]){
obj[0]-> x = 1000;
obj[0]-> y = 30;
}
int main(){
idk *z[5];
obj(z);
cout << z[0]->x;
return 0;
}
I am just trying out how to use pointers. The problem is when I set my array 'z' size to 5 or any number it doesn't do anything, however when I make it 10 it then prints out the correct output. Ive tried pasting the code into an online compiler and it also plays up there but with other numbers. Is my code wrong or missing some things?
In this
idk *z[5];
you declare 5 idk pointers. These are only pointers that you can assign to point at idks, but you have not created any actual idks. When you later dereference the first pointer you get undefined behavior since it's not actually pointing at an idk:
void obj(idk* obj[]){
obj[0]-> x = 1000; // BOOM
Making the array of pointers actually point at idk instances can be made in many different ways. Here's one:
#include <iostream>
class idk{
public:
int x;
int y;
};
void obj(idk* obj[]){
obj[0]-> x = 1000;
obj[0]-> y = 30;
}
int main(){
idk instances[5];
idk *z[5]{
&instances[0],
&instances[1],
&instances[2],
&instances[3],
&instances[4],
}; // now all five point at one idk instance each
obj(z);
std::cout << z[0]->x;
}
Another option would be to skip the pointer array completely:
#include <iostream>
class idk {
public:
int x;
int y;
};
void obj(idk obj[]) {
obj[0].x = 1000;
obj[0].y = 30;
}
int main() {
idk z[5];
obj(z);
std::cout << z[0].x;
}

How to draw a rectangle using a char parameter in C++?

I want to draw and fill a rectangle using C++. The function parameter passed in must be a char, not an int. In my header file the drawing function is this:
void draw(char);
My rectangle.cpp file is this:
void rectangle::draw(char )
{
for(height=0;height<=height;height++)
{
for(width=1;width<=width;width++)
{
cout<<'*';
}
}
}
My main.cpp file is this:
rectangle d1;
d1.draw(char);
When I run the program it gives me the error:
Expected primary expression before 'char'.
I'm using Code::Blocks 13.12. Any ideas to solve this problem?
Your draw is missing a variable. Change draw(char); to draw(char c);
And both for loops need a maximum range, not the same value as the incrementing variable. height<=height; and width<=width;
#include <iostream>
using namespace std;
void draw(char c )
{
int rheight=10;
int rwidth=20;
for(int height=0;height<=rheight;height++)
{
for(int width=1;width<=rwidth;width++)
{
cout<<c;
}
cout<<"\n";
}
}
int main()
{
draw('*');
cout<<"\n";
return 0;
}

Array without parameters in c++

I'm pretty new in c++ althought a bit experienced in java, and my problem it's the next one:
I'm doing a sudoku project where I'm creating an abstract data type of the box and the board. In the board one, I'm creating a bidimesional array of boxes, but when I want to create it as a public data so I can use it in the whole class and not only in the board constructor.
I'm creating it in the board constructor because If I don't create it there, I have no way of knowing the value of each dimension, and if I create the variable Box box[int][int] where I can use it in the class, I've got no way of knowing the dimensions. It'll be better understandable with some code.
This code allows me to create the Box array with the dimensions I want, because it's in the board constructor than when it's created it has as a parameters the number of boxes, but it don't let me use the "casilla" variable in the other part of the class nor other classes:
class tablero{
int filas;
int columnas;
public:
tablero (int filas, int columnas){
this->filas = filas;
this->columnas =columnas;
Casilla casilla[filas][columnas];
}
Casilla getCasilla(int n, int m){
return casilla[n][m]; <- Here shows an error because casilla cannot be resolved.
}
And this other code lets me use the casilla variable, but I have to give it the parameters to the dimensions before I know them:
class tablero{
int filas;
int columnas;
public:
Casilla casilla[0][0];
tablero (int filas, int columnas){
this->filas = filas;
this->columnas =columnas;
}
Casilla getCasilla(int n, int m){
return casilla[n][m];
}
No error, but the dimensions of the casilla array have to be given before I know them, and so, they may be the wrong ones (because the board may have different dimensions.
It's the first time I'm programming in c++, and I'm really frustated with this problem, can anyone help me to find a way to make it so it works both ways? (I already tried to leave both dimensions empty and then in the constructor put casilla[][] = Casilla cas[filas] [columnas] but it gives me an error..)
Thanks for the help everyone. Also, If you think the title is not clear enough, you can suggest one and I'll change it.
The Casilla code is this one:
class Casilla{
int fila;
int columna;
int numero;
public:
// constructor
Casilla(int fila, int columna,int numero)
{
this->fila = fila;
this->columna = columna;
this->numero = numero;
}
};
Thanks everyone for your answers, I've already found the answer I needed from 3 different people. I can't upvote all of you because I still don't have 15 reputation, but when I have it i'll upvote you all. Thanks for all your answers, really. I just need to know what I commented on the checked answer and it'll be all answered.
A solution with an array
//----------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
//----------------------------------------------------------------------------
class Casilla
{
int fila;
int columna;
int numero;
public:
// default constructor
Casilla()
{
this->fila = -1;
this->columna = -1;
this->numero = 0;
}
int GetNumero() {return numero;}
void SetCasilla (int _fila, int _columna) //set a cell position
{
fila = _fila;
columna = _columna;
}
void SetCasilla (int _numero) //set a cell value
{
numero = _numero;
}
void SetCasilla (int _fila, int _columna, int _numero) //set a cell position and value
{
fila = _fila;
columna = _columna;
numero = _numero;
}
};
class Tablero
{
int filas;
int columnas;
Casilla **casilla;
public:
Tablero (int filas, int columnas)
{
this->filas = filas;
this->columnas =columnas;
casilla = new Casilla* [filas];
for (int i = 0; i<filas; i++)
casilla[i] = new Casilla [columnas];
for (int i = 0; i<filas; i++)
for (int j = 0; j<columnas; j++)
casilla[i][j].SetCasilla(i,j); //set the right position for each cell
//the values = 0 by default
}
//destructor
~Tablero()
{
for (int i = 0; i<filas; i++)
delete [] casilla[i];
delete [] casilla;
}
//set a cell value in the table
void ChangeCasillaValue (int _fila, int _columna, int _numero)
{
casilla[_fila][_columna].SetCasilla (_numero);
}
Casilla getCasilla(int n, int m)
{
return casilla[n][m];
}
void PrintTablero ()
{
for (int i = 0; i<filas; i++)
{
for (int j = 0; j<columnas; j++)
std::cout << std::setw(5)<<casilla[i][j].GetNumero();
std::cout << "\n";
}
std::cout << "\n";
}
};
//----------------------------------------------------------------------------
int main()
{
int N = 5, M = 6;
Tablero table(N, M);
table.PrintTablero();
table.ChangeCasillaValue(1,1,-5); //change value in cell(1,1)
table.PrintTablero();
std::cin.get();
return 0;
}
//-----------------------------------------------------------------------------
You have to add a bunch of setters and getters of your own.
But, as a draft, it works.
C-style array dimensions must be known at compile-time in C++. So there is no variant of Casilla casilla[filas][columnas]; that will work.
Instead you should use a container which can hold the data you want to put in it. Use of C-style arrays in C++ is discouraged because they have some strange behaviour and rules, they are mainly there for backwards compatibility.
The simplest option is a 1-dimensional array with runtime size, that is called vector:
class tablero{
int filas;
int columnas;
std::vector<Casilla> casilla;
public:
tablero (int filas, int columnas)
: filas(filas), columnas(columnas), casilla(filas * columnas)
{ }
Casilla getCasilla(int f, int c) const
{
return casilla[f * columnas + c];
}
};
Note the use of the constructor initializer list. You should provide initial values for class members this way, instead of using assignment statements inside the constructor.
In your first example, in your constructor, the line
Casilla casilla[filas][columnas];
declares casilla an array of arrays of Casilla objects local to your constructor. Once your constructor returns, casilla goes out of scope. There is no casilla member variable or local variable in your getCasilla function, so of course it cannot be resolved.
In your second example, your class has a public member casilla declared as 0 by 0 array of Casilla objects. Your getCasilla function would return the item in the nth row and mth column of the 0 by 0 array. In C++, there is no bound checking on array dereferences, so this is returning some out of bounds memory location and is very bad.
You can create dynamic C arrays yourself by using malloc and free, but since you are using C++ it will be easier to just use std::vector.
For example, you could use:
#include <iostream>
#include <vector>
class Casilla
{};
class tablero
{
int filas_;
int columnas_;
std::vector<std::vector<Casilla> > casilla_; // a vector of vectors of Casillas
public:
tablero(int filas, int columnas) : filas_(filas), columnas_(columnas),
casilla_(filas, std::vector<Casilla>(columnas))
// The above is an initialization list
// We initialize casilla_ as a vector of filas vectors of columnas Casillas
{}
std::vector<std::vector<Casilla> > getCasilla() const
{
return casilla_;
}
};
int main(int argc, const char* argv[])
{
tablero t(3, 3);
std::cout << "casilla rows: " << t.getCasilla().size() << std::endl;
std::cout << "casilla cols: " << t.getCasilla()[0].size() << std::endl;
return 0;
}
First Casilla casilla[filas][columnas]; needs to be a class variable so it's accessible to all methods.
Second the sizes of rows and columns must be a fixed number e.g Casilla casilla[9][9];
If it need to be dynamically allocated you could you Vectors or Vectors of Vectors.
If it's 2d array, you can still create it as 1d array, but depends which is best for your purposes.

Swap 2D int array elements according to user input using printf and scanf

How do i swap the elements in a 2D int array according to use input? For example i have a 2x2 matrix with elements
int c[2][2]=
{
{1,2, },
{3,4, }
};
the user inputs which area to swap like: c[0][0] and c[0][1] then display the new results. Thanks
#include <stdio.h>
#include <stdlib.h>
void swap(int c[2][2],int &x1,int &y1,int &x2,int &y2)
{
int temp = c[x1][y1];
c[x1][y1] = c[x2][y2];
c[x2][y2] = temp;
}
int main(void)
{
int c[2][2]=
{
{1,2, },
{3,4, }
};
int x,y;
int x1,x2,x3,x4,x5,y1,y2,y3,y4,y5;
for(x=0;x<2;x++)
{
for(y=0;y<2;y++)
{
printf("\t%d",c[x][y]);
}
printf("\n");
}
printf("\nEnter 1st value to be swapped:\n");
printf("Row\n");
scanf("%d",&x3);
printf("Column\n");
scanf("%d",&y3);
printf("\nEnter 2nd value to be swapped:\n");
printf("Row\n");
scanf("%d",&x4);
printf("Column\n");
scanf("%d",&y4);
if((x3==1&&y3==1)&&(x4==1&&y4==2))
{
swap(c[0][0],c[0][1]);
}
for(x=0;x<2;x++)
{
for(y=0;y<2;y++)
{
printf("\t%d",c[x][y]);
}
printf("\n");
}
system("pause");
return ;
}
It looks like you just want to do this:
swap(c[x3-1][y3-1],c[x4-1][y4-1]);
But before you do that, you'll need to sanitise the variables to ensure they are within the range of the array.

trying to create a dice game using function c++

i am trying to have a function determine the result
a. If the numbers add up to 5, 7, or 12, then the player wins, and the function should return an indication of this (use some integer to represent a win).
b. If the numbers add up to 2, 4, or 11, then the player loses, and the function should return an indication of this (once again, use an integer).
c. If the numbers add up to anything else, then the game is a draw and the function should say this (by way of an integer).
question, do i need a different func for winner, loser, and draw?
and what how can i return a integer to main to let main know that if we have a winner a loser a draw.
just learning to program any help would be greatly appreciated
//function
int outcome(int, int)
{
int die1;
int die2;
int winner;
int loser;
int draw;
if (die1&&die2==5||7||12)
return 99;
if (die1&&die2==2||4||11)
return loser;
else
return draw;
}
// func to get a random number
int rollDice()
{
int roll;
roll = (rand()%6)+1;
return roll;
}
the main func
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
double die1=0;
double die2=0;
int winner=0; //counter for winners
int loser=0; //counter for losers
int draw=0; //counter for draw
//func to determine the outcome
int outcome(int, int);
//func for random numbers
int rollDice();
int outcome(int, int)
if (return==99)
cout <<"winner";
Your code has several syntax errors. If I want to, say, make a function to add two integer numbers, I'd do something like this:
int add(int a, int b) //VARIABLES MUST CARRY A NAME!
{
return a+b;
}
If you want to work with conditions, do this:
if(a==5 && b==6 || a==6 && b==7) //Just as an example
Your fixed condition would be this:
if (die1+die2==5 || die1+die2==7 || die1+die2==12)
Also, study variable scope. Let's say I have the following:
int main()
{
int myVar = 1;
}
int anotherFunction()
{
println("%d", myVar); //This will cause an error, because myVar doesn't exist here, it only exists in main()
}
These are the most notable errors I can see in your code.