I'm trying to build and print a 2d array but its showing up as empty when I try to print it out so there's an error somewhere but I cant find it. Can someone help? I added the code for initializing the array.
#ifndef MAZE_HPP_
#define MAZE_HPP_
#include <fstream>
#include <vector>
#include <string>
class Maze
{
public:
Maze(int size);
~Maze() {}
enum Direction { DOWN, RIGHT, UP, LEFT };
// Implement the following functions:
// read maze from file, find starting location
void readFromFile(std::ifstream &f);
// make a single step advancing toward the exit
void step();
// return true if the maze exit has been reached, false otherwise
bool atExit();
// set row and col to current position of 'x'
void getCurrentPosition(int &row, int &col);
//print function
void printMaze();
// You can add more functions if you like
private:
// Private data and methods
int size, rowX, colY;
char matrix[30][30];
};
#endif /* MAZE_HPP_ */
void Maze::readFromFile(std::ifstream &f) {
std::string line;
int i, j;
getline(f, line);
for(i = 0; i < size; i++) {
getline(f, line);
for(j = 0; j < size; j++) {
matrix[j][i] = line[j];
}
}
f.close();
}
void Maze::printMaze() {
int i, j;
for(i = 0; i < size; i++) {
for(j = 0; j < size; j++) {
std::cout << matrix[i][j] << "";
std::cout << "line";
}
std::cout << std::endl;
}
}
The initialization does not matter here although it is good practice. Back to the problem: there can be several reasons
1. You have passed zero or negative number for size in the constructor when you create a Maze object.
2. You have passed positive number for size but forgot to assign it to the size variable in the constructor.
If it enters into the loop in print function and shows the string "line" size times then it means it can not read anything from file.
It would be helpful if you send full code or at least the constructor.
Related
I need to fill in the blanks on pieces of code I've already been given. The problem is this:
The following class (long_number) represents a number of any length from 1 to 60. The default constructor generates the number 0. Need a print function, which prints the long_number. A constructor that turns an array of chars into a long_number.
I've gotten a few of the pieces started. Still trying to work out some of the later stuff. A lot of it is not quite making sense.
The places I put in code are:
the 1 in the statement int number [];
long_number::long_number in the no-arg constructor
1 in size =
the 0 and ++ in the first for loop in the constructor
the i in the number[i] = 0; statement
char and the ::long_number for the parameter in the 2nd constructor
_size in the statement size =
the greater than or equal to in the for statement
void long_number:: at the start of the print function
the -1 after max_digits and the i, in the for loop for (int i = max_digits - 1; i < max_digits; i++)
number and i in the cout statement
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class long_number {
private:
static const int max_digits = 60;
int number[1];
int size;
public:
long_number();
long_number(char a[], int _size);
void print();
};
long_number::long_number() {
size = 1;
for (int i = 0; i < max_digits; i++) {
number[i] = 0;
}
}
long_number::long_number(char input[], int _size) {
size = _size;
for (int i = 1; i <= size; i++) {
number[size -i] = (char) input[size - 1] - (int)'?';
}
void long_number::print() {
for (int i = max_digits - 1; i < max_digits; i++) {
cout << number[i];
}
cout << endl;
}
int main()
{
long_number n1;
n1.print();
cin.get();
return 0;
}
I question how I did the for loop in the print function and I need help with the constructor with parameters. The ? is one place I'm not sure what to put. There isn't anything similar in the problems I see in the textbook and he didn't show us any examples like this in class.
The ? is '0',the char array save the char '0' to '9'.And the function is save int to int number[].So need a change.
And others which need change is:
number[] define
int number[max_digits];
the print function, i++ change to i--
Intermittently, Visual Studio throws an exception when running my code. I say intermittently because I've been able to successfully run my code without an error. The error was thrown after I created the function "print_Days."
The exception thrown is:
Debug Assertion Failed!
File: minkernel\crts\ucrt\corecrt_internal_string_templates.h
Line: 81
Expression: (L"Buffer is too small" && 0)
The function reads from a .txt file that has 7 days of the week listed (Monday thru Sunday) and then alphabetically sorts the days in a 2D c-string array (professor is making us use c-string instead of string unfortunately).
Here is all of my code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
//Constants for 2D array
const int NUM_OF_ROWS = 7; //Seven days listed in the file
const int NUM_OF_COLS = 10; //Longest word is 9 chars long, plus \0
void get_Days(ifstream& file, char days[][NUM_OF_COLS], int rows);
void sort_Days(char days[][NUM_OF_COLS], int rows);
void print_Days(const char days[][NUM_OF_COLS], const int rows);
void get_Days(ifstream& file, char days[][NUM_OF_COLS], int rows) {
//Read from text file and return day
for (int i = 0; i < rows; ++i)
{
file >> days[i];
}
}
void sort_Days(char days[][NUM_OF_COLS], int rows) {
//Sort the array alphabetically
char temp[NUM_OF_COLS];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
if (strcmp(days[j - 1], days[j]) > 0)
{
strcpy_s(temp, days[j - 1]);
strcpy_s(days[j - 1], days[j]);
strcpy_s(days[j], temp);
}
}
}
}
void print_Days(const char days[][NUM_OF_COLS], const int rows) {
//Print the sorted array to the console
for (int i = 0; i < NUM_OF_ROWS; ++i)
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < NUM_OF_COLS; j++)
{
cout << days[i][j] << endl;
}
}
}
int main() {
//This program reads from a file (days.txt), sorts the days
// alphabetically, and then prints the result to the console.
ifstream infile("days.txt");
char days[NUM_OF_ROWS][NUM_OF_COLS];
if (!infile)
{
cout << "File (days.txt) does not exist." << endl;
return 1;
}
get_Days(infile, days, NUM_OF_ROWS);
infile.close();
sort_Days(days, NUM_OF_ROWS);
print_Days(days, NUM_OF_ROWS);
return 0;
}
A few things are wrong with the code:
sort_Days
The sort_Days algorithm is throwing errors because you are trying to index days[j - 1] when the nested for loop starts with j = 0. So your initial index is out of bounds.
Furthermore, it seems like you are trying to perform bubble sort on the c-style strings, but your bubble sort implementation is incorrect. Please consult this page for how to implement a simple bubble sort. Hint: the for loop conditional, strcmp and strcpy_s indices need some tweaking.
print_Days
Your print_Days function is incorrect. Here is a version that prints out each c-style string instead of each char within the string:
void print_Days(const char days[][NUM_OF_COLS], const int rows)
{
for (int j = 0; j < rows; j++)
{
cout << days[j] << endl;
}
}
You should know that std::cout understands that when you pass it a c-style string (i.e. the char[NUM_OF_COLS] within days), it means you want to print out the whole string up to the null-terminator.
Your for loop termination conditional was also wrong, because you had j < NUM_OF_COLS, whereas days actually is an array with NUM_OF_ROWS elements, and each element is an array of NUM_OF_COLS size. The way you had it had indexing out of bounds of the days array.
And while I am nitpicking
Try not to use using namespace::std;, there are plenty of reasons why you shouldn't..
Below is my current code for my latest assignment and I cannot figure out what the problem is printing the array. Forgive me for the crappy code, in my class we were thrown into C++ and none of us have ever used it before so it may be a simple mistake but no one in the house can help me.
Header file DynamicArray.h:
//
// DynamicArray.h
///#include <rpcndr.h>
#ifndef DYNAMIC_DYNAMICARRAY_H
#define DYNAMIC_DYNAMICARRAY_H
#endif //DYNAMIC_DYNAMICARRAY_H
// union
// intersection
// relative complement
// insertion - if the element is already in the set, then nothing happens
// deletion - if the element is not in the set, then nothing happens
// query to check whether an element is in a set
// query to find the number of number of elements in a set
// display the set
//destructor
// copy constructor
// ***********************************overloading assignment operator***************************************************
class DynamicArray{
public:
DynamicArray(int size);
DynamicArray(const DynamicArray &original, int Size);
/// DynamicArray(int Size);
~DynamicArray();
void Union();
void Intersection();
void Complement();
int Insert(int position, int entry, int size);
int Delete(int position, int entry, int size);
bool Qelement(int size, int entry);
int Qset(int size);
int size = 20;
int *array;
};
//
//
//
Source file DynamicA.cpp- here I define the constructors and member functions:
//
// DynamicA.cpp
//
//Union();
//Intersection();
//Complement();
//Insert();
//Delete();
//Qelement();
//Qset();
#include <iostream>
#include "DynamicArray.h"
using namespace std;
DynamicArray::DynamicArray(int &size = 30){
size = 20;
*array = new int[size];
for(int i = 0; i < size; i++){
array[i] = 0;
};
}
/// DynamicArray::DynamicArray(int Size) {
///
/// }
DynamicArray::DynamicArray(const DynamicArray &original, int size) {
size = original.size;
array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = original.array[i];
}
}
DynamicArray::~DynamicArray(){
delete[] array;
}
void DynamicArray::Union(){
}
void DynamicArray::Intersection() {
}
void DynamicArray::Complement(){
}
int DynamicArray::Insert(int position, int entry, int size) {
if(!Qelement()){
for(int i = size+1; i > position+1; i--){
array[i] = array[i-1];
}
array[position] = entry;
}
}
int DynamicArray::Delete(int position, int entry, int size){
for(int i = 0; i < size; i++){
if(array[i] == entry) {
for(int x = i; x < size; i++){
array[x] = array[x+1];
}
size--;
}
}
}
bool DynamicArray::Qelement(int size, int entry) {
for(int i = 0; i < size; i++){
if(array[i] == entry){
return true;
}
}
}
int DynamicArray::Qset(int size){
return size;
}
main.cpp - this is where my issue is. The error I continue to receive is that dArray is not an array.
//main.cpp
#include <iostream>
//#include <DynamicArray.h>
#include "DynamicArray.h"
//#include "DynamicA.cpp"
//using namespace std;
int main() {
DynamicArray dArray();
for(int i = 0; i < array; i++) {
cout << dArray[i];
}
}
Your class DynamicArray is not an array, the compiler has it right. It's just a class you've defined. For your code to work, you need to overload DynamicArray::operator[](int), for example, like so:
#include <cassert>
int DynamicArray::operator[](int idx)
{
assert(idx < size);
return array[i];
}
The reason is that operator[] is only defined for the built-in array type, where it has an established meaning and understood by the compiler. But you have defined an arbitrary class, and your understanding that it is an array is only your understanding, i.e. an assumption, which in no way is perceived by the compiler, so to say.
Now, let me point this one out before you run into issues caused by that mistake: the fields size and array must be private or at least protected! Read up on encapsulation in C++, as well as the other two or three founding principles of this language. You may wonder how to access the size of the array form the outside given this change, well that's where the so-called getter-setter methods come into play. Define int DynamicArray::size() const { return size; } to let the array tell its size to its clients.
Now you can use the previously defined operator[](int) with int size():
DynamicArray myArray(5);
for(int i = 0; i < myArray.size(); ++i)
std::cout << myArray[i] << " ";
Other errors: two pointed out by#crashmstr: *array = new int[size]; should be array = new int[size]; and DynamicArray myArray(); isn't going to build, since this calls the undefined default constructor.
Currently I am getting an runtime "assertation error"
Here is the error:
I'm reading words from a text file into dynamically allocated arrays.
this block of code is where I am filling the new arrays.
I know the problem is being caused by this block of code and something about my logic is off just can't see what it is.
//fill new arrays
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i];
New_WordCount[y] = WordCount[i];
y++;
}
}
}
Also how would I pass this dynamically allocated 2D array to a function? (the code really needs to be cleaned up as a whole)
char** SentenceArry = new char*[NUM_WORDS]; //declare pointer for the sentence
for( int i = 0; i < NUM_WORDS; i++)
{
SentenceArry[i] = new char[WORD_LENGTH];
}
Here is the full extent of the code.. help would be much appreciated!
Here is what is being read in:
and the current output (the output is how it's suppose to be ):
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <iomanip>
using std::setw;
using std::left;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
int main()
{
const int NUM_WORDS = 17;//constant for the elements of arrays
const int WORD_LENGTH = 50;//constant for the length of the cstrings (NEED TO GIVE THE VALUE ZERO STILL!)
short word_entry = 0; //declare counter
short new_numwords= 0; //declare new word count
char EMPTY[1][4]; //NULL ARRAY
EMPTY[0][0] = '\0';//define it as null
char** SentenceArry = new char*[NUM_WORDS]; //declare pointer for the sentence
for( int i = 0; i < NUM_WORDS; i++)
{
SentenceArry[i] = new char[WORD_LENGTH];
}
int WordCount[NUM_WORDS];//declare integer array for the word counter
for(int i = 0; i < NUM_WORDS; i++)//fill int array
{
WordCount[i] = 1;
}
int New_WordCount[NUM_WORDS] = {0};
ifstream read_text("DataFile.txt"); //read in our text file
if (read_text.is_open()) //check if the the file was opened
{
read_text >> SentenceArry[word_entry];
//REMOVE PUNCTUATION BEFORE BEING READ INTO THE ARRAY
while (!read_text.eof())
{
word_entry++; //increment counter
read_text >> SentenceArry[word_entry]; //read in single words of the text file into the array SentenceArry
char* ptr_ch;//declare our pointer that will find chars
ptr_ch = strstr( SentenceArry[word_entry], ",");//look for "," within the array
if (ptr_ch != NULL)//if true replace it with a null character
{
strncpy( ptr_ch, "\0" , 1);
}//end if
else
{
ptr_ch = strstr( SentenceArry[word_entry], ".");//look for "." within the array
if (ptr_ch != NULL)//if true replace it with a null character
{
strncpy( ptr_ch, "\0" , 1);
}//end if
}//end else
} //end while
}//end if
else
{
cout << "The file could not be opened!" << endl;//display error message if file doesn't open
}//end else
read_text.close(); //close the text file after eof
//WORD COUNT NESTED FOR LOOP
for(int y = 0; y < NUM_WORDS; y++)
{
for(int i = y+1; i < NUM_WORDS; i++)
{
if (strcmp(SentenceArry[y], EMPTY[0]) == 0)//check if the arrays match
{
y++;
}
else
{
if (strcmp(SentenceArry[y], SentenceArry[i]) == 0)//check if the arrays match
{
WordCount[y]++;
strncpy(SentenceArry[i], "\0" , 3);
}//end if
}//end if
}//end for
}//end for
//find how many arrays still contain chars
for(int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
new_numwords++;
}
}
//new dynamic array
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[new_numwords];
}
//fill new arrays
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i];
New_WordCount[y] = WordCount[i];
y++;
}
}
}
//DISPLAY REPORT
cout << left << setw(15) << "Words" << left << setw(9) << "Frequency" << endl;
for(int i = 0; i < new_numwords; i++) //compare i to the array constant NUM_WORDS
{
cout << left << setw(15) << New_SentenceArry[i] << left << setw(9) << New_WordCount[i] << endl; //display the contents of the array SentenceArry
}
//DEALLOCATION
for( int i = 0; i < NUM_WORDS; i++)//deallocate the words inside the arrays
{
delete [] SentenceArry[i];
}
for(int i = 0; i < new_numwords; i++)
{
delete [] New_SentenceArry[i];
}
delete [] SentenceArry; //deallocate the memory allocation made for the array SentenceArry
delete [] New_SentenceArry;//deallocate the memory allocation made for the array New_SentenceArry
}//end main
There are several issues with the code, not withstanding that this could be written using C++, not C with a sprinkling of C++ I/O..
Issue 1:
Since you're using c-style strings, any copying of string data will require function calls such as strcpy(), strncpy(), etc. You failed in following this advice in this code:
for( int y = 0; y < new_numwords; y++)
{
for( int i = 0; i < NUM_WORDS; i++)
{
if (!strcmp(SentenceArry[i], EMPTY[0]) == 0)
{
New_SentenceArry[y] = SentenceArry[i]; // This is wrong
New_WordCount[y] = WordCount[i];
y++;
}
}
}
You should be using strcpy(), not = to copy strings.
strcpy(New_SentenceArry[y], SentenceArry[i]);
Issue 2:
You should allocate WORD_LENGTH for both the original and new arrays. The length of the strings is independent of the number of strings.
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[new_numwords];
}
This should be:
char** New_SentenceArry = new char*[new_numwords]; //declare pointer for the sentence
for( int i = 0; i < new_numwords; i++)
{
New_SentenceArry[i] = new char[WORD_LENGTH];
}
Issue 3:
Your loops do not check to see if the index is going out of bounds of your arrays.
It seems that you coded your program in accordance to the data that you're currently using, instead of writing code regardless of what the data will be. If you have limited yourself to 17 words, where is the check to see if the index goes above 16? Nowhere.
For example:
while (!read_text.eof() )
Should be:
while (!read_text.eof() && word_entry < NUM_WORDS)
Issue 4:
You don't process the first string found correctly:
read_text >> SentenceArry[word_entry]; // Here you read in the first word
while (!read_text.eof() )
{
word_entry++; //increment counter
read_text >> SentenceArry[word_entry]; // What about the first word you read in?
Summary:
Even with these changes, I can't guarantee that the program won't crash. Even it it doesn't crash with these changes, I can't guarantee it will work 100% of the time -- a guarantee would require further analysis.
The proper C++ solution, given what this assignment was about, is to use a std::map<std::string, int> to keep the word frequency. The map would automatically store similar words in one entry (given that you remove the junk from the word), and would bump up the count to 1 automatically, when the entry is inserted into the map.
Something like this:
#include <string>
#include <map>
#include <algorithm>
typedef std::map<std::string, int> StringMap;
using namespace std;
bool isCharacterGarbage(char ch)
{ return ch == ',' || ch == '.'; }
int main()
{
StringMap sentenceMap;
//...
std::string temp;
read_text >> temp;
temp.erase(std::remove_if(temp.begin(), temp.end(), isCharacterGarbage),temp.end());
sentenceMap[temp]++;
//...
}
That code alone does everything your original code did -- keep track of the strings, bumps up the word count, removes the junk characters from the word before being processed, etc. But best of all, no manual memory management. No calls to new[], delete[], nothing. The code just "works". That is effectively 5 lines of code that you would just need to write a "read" loop around.
I won't go through every detail, you can do that for yourself since the code is small, and there are vast amounts of resources available explaining std::map, remove_if(), etc.
Then printing out is merely going through the map and printing each entry (string and count). If you add the printing, that may be 4 lines of extra code. So in all, practically all of the assignment is done with effectively 10 or so lines of code.
Remove below code.
for(int i = 0; i < new_numwords; i++)
{
delete [] New_SentenceArry[i];
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a 2D fixed size object array of "spot" class
Spot map[row][col];//row & col are dynamic changed integer
I want to pass it to a function
bool isFilled(int row,int col,Spot[row][col]){}
How to define the function? How to delete this array ?Please see my code. Thanks for your help.
Spot.h
#ifndef SPOT_H
#define SPOT_H
class Spot
{
private:
bool isBunny;
int nextCycle;
public:
static const int UP = 0;
static const int RIGHT = 1;
static const int DOWN = 2;
static const int LEFT = 3;
static const int SLEEP = 4;
virtual void setSpot(bool newIsBunny);
Spot();
~Spot();
virtual int getNextCycle();
virtual void setNextCycle();
virtual bool getIsBunny();
virtual void makeBunny();
};
void Spot::setSpot(bool newIsBunny)
{
isBunny = newIsBunny;
nextCycle = UP;
}
Spot::Spot()
{
isBunny = false;
nextCycle = UP;
}
Spot::~Spot()
{
}
void Spot::setNextCycle()
{
if (nextCycle != SLEEP)
{
nextCycle++;
}
}
int Spot::getNextCycle()
{
return nextCycle;
}
bool Spot::getIsBunny()
{
return isBunny;
}
void Spot::makeBunny()
{
if (!isBunny)
nextCycle = UP;
isBunny = true;
}
#endif /* SPOT_H */
Bunny.cpp
#include "Spot.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <boost/algorithm/string.hpp>
using namespace std;
static string line;
static ifstream inFile;
static ofstream outFile;
bool isFilled(int x, int y, Spot **myMap);
int main () {
int numSims = 0;
inFile.exceptions ( ifstream::failbit | ifstream::badbit );
try {
inFile.open ("/home/mike/Desktop/input.txt");
outFile.open ("/home/mike/Desktop/output.txt");
// while(!inFile.eof())
{
getline (inFile,line);
numSims= atoi(line.c_str());
//cout<<"numSims: "<<numSims<<endl;
for (int i = 0;i < numSims;i++)
{
int minPerCycle = 1;
getline (inFile,line);
minPerCycle= atoi(line.c_str());
//cout << "minPerCycle: "<<minPerCycle <<endl;
int row = 0;
int col = 0;
getline (inFile,line);
std::vector<std::string> xy;
boost::split(xy, line, boost::is_any_of(" "));
row=atoi(xy.at(0).c_str());
col=atoi(xy.at(1).c_str());
//cout <<"row: "<< row<<endl;
//cout << "col: "<<col<<endl;
Spot** myMap = new Spot* [col];
for(int i = 0; i < col; ++i)
myMap[i] = new Spot [row];
//std::vector<std::vector<Spot> > myMap(x, std::vector<Spot>(y));
for (int i = 0;i < row;i++)
{
getline (inFile,line);
//cout<<line<<endl;
for (int j = 0;j < col;j++)
{
if (line[j] == 'B')
{
myMap[i][j].setSpot(true);
}
else
{
myMap[i][j].setSpot(false);
}
}
}
int numCycles = 1;
if (isFilled(row,col,myMap))
{
numCycles = 0;
}
while (!isFilled(row,col,myMap))
{
numCycles++;
for (int j = 0;j < row;j++)
{
for (int k = 0;k < col;k++)
{
if (myMap[j][k].getIsBunny())
{ //cout<< j<<" "<<k<<" " <<"true"<<endl;
switch (myMap[j][k].getNextCycle())
{
case Spot::UP :
if (j>0)
myMap[j-1][k].makeBunny();
break;
case Spot::RIGHT :
if (k<col-1)
myMap[j][k + 1].makeBunny();
break;
case Spot::DOWN :
if (j<row-1)
myMap[j+ 1][k].makeBunny();
break;
case Spot::LEFT :
if (k>0)
myMap[j][k - 1].makeBunny();
break;
}
myMap[j][k].setNextCycle();
}
//cout<< j<<" "<<k<<" " <<"outside"<<endl;
}
}
}
int time = numCycles*minPerCycle;
outFile<<"It took " <<time <<" minutes for the bunnies to take over the world!\n";
cout<<"It took " <<time <<" minutes for the bunnies to take over the world!\n";
for(int i=0; i < col; i++) {
delete [] myMap[i];
}
delete myMap;
}
}
inFile.close();
outFile.close();
}
catch (ifstream::failure e) {
cout << "Exception opening/reading file";
}
return 0;
}
bool isFilled(int row, int col,Spot **myMap)
{
for (int i = 0;i < row;i++)
{
for (int j = 0;j < col;j++)
{
if (!myMap[i][j].getIsBunny())
{
//cout<<"true ";
return false;
}
//else
// cout<<"false ";
}
//cout<<endl;
}
return true;
}
Have to tried passing with pointers?
static bool isFilled(int row, int col,Spot** yourMap)
I'm unsure if Spot myMap[row][col] will be accepted by the compiler as row and col seem to be set at runtime.
You may need to allocate memory in the following manner
Spot** myMap = new Spot* [col];
for(int i = 0; i < col; ++i)
myMap[i] = new Spot [row];
Deleting the memory would require you to use a similar for loop but remember to call delete []
I think you can just send a reference to the 2D array into the method you want to use the 2D array with.
bool isFilled(int row, int col, Spot &m){ // if you want a fix position in the array
// Code
}
If you want to delete the array you have to use the delete operator.
First you have to delete all the arrays which the pointer array points to, ie
for(int i=0; i < size; i++) {
delete [] spot[i]; // Depends on what you have called the array
}
Then you have to delete the array of pointers with
delete [] spot;
Spot myMap[row][col];
This is not legal C++ code. You can do this in C99 but not in C++.
You have two basic choices in C++:
Use a one dimensional array that you treat as if it were a 2D array.
Use a ragged 2D array instead of a contiguous 2D array.
The key advantage of using a one dimensional array is that it is fast. This is the way to go if you need speed. Graphics programmers often use this approach because they need that speed. The downside is that you have to convert your 2D indices to a single index. For example, map[i][j] might become map[i*col+j] (row major order) or map[i+j*row] (column major order).
The key advantage of using a ragged array is that the indexing is natural. The downsides are that there are many more pieces of memory to manage and access is considerably slower. With a flattened array, access comprises a small number of integer operations and a single memory lookup. The ragged array requires two memory lookups.
This is C++, so my suggestion is to make your map a class. Provide a non-default constructor with a row and column size that allocates the memory, a destructor (if needed) to clean up. If you use std::vector as the underlying storage mechanism, it will do the allocation and cleanup for you. Provide an overload of operator() to act as an index mechanism into your map. Now the mechanism that you are using to represent your map is hidden. You can start with a vector of vectors, and if that's too slow, switch to the flattened array approach.