I'm writing a program which finds exit from maze. I have a multidimentinal array representing the actual maze.
const int size = 12;
char maze[ size ][ size ] = {
"############",
"#...#......#",
"..#.#.####.#",
"###.#....#.#",
"#....###.#..",
"####.#.#.#.#",
"#..#.#.#.#.#",
"##.#.#.#.#.#",
"#........#.#",
"######.###.#",
"#......#...#",
"############",
};
VS C++ gives me a warning message, saying that size is too small for such array. I guess it's because there must be also '\0' symbol in each line. How do I initialize char array without '\0' symbols? I don't want to initialize size with value 13 because it's will be too confused to use this constant for functions (printing array, making move etc.) Is there any way to do it?
Also, how to pass this array to function void mazeTraverse using pointer?
int main()
{
mazetraverse(maze)
}
void mazeTraverse(char (*maze)[ size ])
Such code doesn't works...
You need to account for the NULL character at the end of the string:
char maze[size][size + 1] = { /* */ };
Alternatively, for more flexibility, you can do:
char *maze[size] = { /* */ };
I see you're using C++. Is there any reason you're not using std::string?
std::string maze[size] = { /* */ };
It's a lot more flexible; now you just change the prototype to:
void mazeTraverse(std::string maze[]);
If you're even more insane, you'll use std::vector<std::string>.
EDIT: I recommend learning a bit about std::string. It works just like a char* but you don't have to manually allocate it/etc. For example:
std::string mystring = "lol";
mystring = "lololol"; // perfectly legal!
std::cout << mystring[0] << "\n";
// Or: printf("%c\n", mystring[0]);
char* sz[8];
strcpy(sz, mystring[0].c_str());
// And so on...
So long as you're using C++, why not just make a simple class?:
class Maze {
public:
Maze(int width, const std::string& data)
:width_(width),
data_(data.begin(), data.end()) {
}
char operator()(int row, int column) const {
return data_[width_*row + column];
}
private:
int width_;
std::vector<char> data_;
};
You can initialize it easily by taking advantage of the fact that subsequent string literals, like "foo" "bar", are implicitly concatenated into "foobar":
Maze my_maze(12,
"############"
"#...#......#"
"..#.#.####.#"
"###.#....#.#"
"#....###.#.."
"####.#.#.#.#"
"#..#.#.#.#.#"
"##.#.#.#.#.#"
"#........#.#"
"######.###.#"
"#......#...#"
"############");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With