将类级别的 2D 数组变量设置为传入值 - C++ [英] Setting class level 2D Array variable to passed in value - C++
问题描述
我正在尝试制作一个解谜程序,虽然算法是合理的(至少在我的脑海中),但我遇到了二维数组的障碍.我来自 C# 和 Java,所以语法让我很伤心.
I'm attempting to make a maze-solving program, and while the algorithm is sound (at least in my head), I've been running into a roadblock with 2D arrays. I'm coming from C# and Java, so the syntax is giving me grief.
这是一个 SSCCE:
Here's an SSCCE:
//Main.cpp
#include "MazeSolver.h"
int main()
{
MazeSolver mazeSolver;
char maze[51][51] = { }; // Not bothering to show code for populating the array
mazeSolver.setMaze(maze);
}
<小时>
//MazeSolver.cpp
#include "MazeSolver.h"
MazeSolver::MazeSolver() { }
void MazeSolver::setMaze(char maze[51][51])
{
this->maze = maze;
}
<小时>
//MazeSolver.h
#ifndef _MAZESOLVER_H
#define _MAZESOLVER_H
class MazeSolver
{
private:
char **maze; // This is likely the problem, I'm at wits end in regards to
// what notation is needed here. I do not want to hard-copy
// the entire array, I just need to access it (via pointer)
// I've also tried just using char maze[51][51] here, char *maze, etc...
public:
MazeSolver();
void setMaze(char maze[51][51]);
}
推荐答案
这是 C++ 的怪癖之一.
This is one of the weird quirks of C++.
C++ 2D 数组不是锯齿状数组.当你声明 char maze[51][51] 时,它实际上分配了 1 个 51*51 成员长度的连续数组.sizeof(迷宫) == 51*51
.当你取消引用一个值时,maze[a][b]
,它实际上做的是*(maze+51*a+b)
.所有这些都在幕后.
C++ 2D arrays are NOT jagged arrays. When you declare char maze[51][51], it actually allocates 1 contiguous array 51*51 members long. sizeof(maze) == 51*51
. When you dereference a value, maze[a][b]
, what it actually does is *(maze+51*a+b)
. All this is under the hood.
锯齿状数组是一个数组数组,一个字符**.在这种情况下,您有一个包含 51 个指针大小 == (51*sizeof(void*)) 的数组.在每个位置,指针指向一个完全不同的内存位置,分配给51个成员长.
A Jagged Array is an array of arrays, a char**. In this case, you have an array of 51 pointers size == (51*sizeof(void*)). In each position, the pointer points to a completely different memory location, allocated to 51 members long.
这很烦人,因为您不能只转换两者,即使是强制转换也是如此.您必须处理奇怪的语法,例如 char (*maze)[51]
来获取指向二维数组的指针.
This is ANNOYING because you can't just convert the two, even by casting. You have to deal with weird syntax, such as char (*maze)[51]
to get a pointer to the 2D array.
更烦人的是以下情况:
int foo(int maze[51][51])
{
return sizeof(maze);
}
int maze[51][51];
int main(int argc, char** argv)
{
std::cout << sizeof(maze) << std::endl;//return 51*51*sizeof(int);
std::cout << foo(maze) << std::endl;//return 8, sizeof(void*);
}
所以它隐式地按引用传递,而不是按值传递,这与 C++ 的所有其余部分相反.
So it implicitly passes by reference, not by value, which is opposite all the rest of C++.
tl;博士;
指向二维数组的指针的正确语法是char (*maze)[51];
.您的语法用于锯齿状数组(数组数组),这在 C++ 中是不同的.
The correct syntax for a pointer to a 2D array is char (*maze)[51];
. Your syntax is for a jagged array (arrays of arrays) which is NOT the same thing in C++.
这篇关于将类级别的 2D 数组变量设置为传入值 - C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!