![](/img/trans.png)
[英]What is the difference between const int*, const int * const, and int const *?
[英]can't figure out difference between int[3][3] and int(* const)[3]
我有以下代码:
int board[3][3]; // I am ommiting initialization code for board here so as not to clutter it.
typedef std::vector<std::pair<int [3][3], int> > History;
History hist = History();
const std::pair<int[3][3], int> p = std::make_pair(board, cell);
hist.push_back(p);
但是用g ++编译会给我这个我无法理解的错误:
In file included from /usr/include/c++/4.7/bits/stl_algobase.h:65:0,
from /usr/include/c++/4.7/vector:61,
from performancesystem.h:29:
/usr/include/c++/4.7/bits/stl_pair.h: In instantiation of
‘std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 =
int (*)[3]; _U2 = int; _T1 = int [3][3]; _T2 = int]’:
Test.cpp:74:65: required from here
/usr/include/c++/4.7/bits/stl_pair.h:111:39: error: incompatible types in
assignment of ‘int (* const)[3]’ to ‘int [3][3]’
我总是在理解C ++中的指针和数组之间的区别时遇到这个问题。 他们不应该是同一个人吗? 谁能帮我吗?
您遇到的问题不是数组指针差异(很大)。
问题在于数组不能在赋值中按值复制。 将C数组包装在类中可以解决,或者更好-使用标准数组。
在某些情况下,数组可以转换为指针。 您尝试的其他方法永远不会发生任何转换。
要继续前进,您应该停止直接使用数组。 它们在C ++中相当无用。 我会写一个新的类(如果愿意,也可以写一个struct)
class Board
{
...
private:
int sq[3][3];
};
typedef std::vector<std::pair<Board, int> > History;
这样,您将停止使用无用的数组,并且不会对数组和指针感到困惑。
与指针只有在动态调整结构通常实现不能怪你,因为阵列的区别。
数组int a [3] [4] [5] [6]例如是从内存中线性分配的。 它包含3 * 4 * 5 * 6个单位,其中a [2] [3] [4] [0] ... a [2] [3] [4] [5]位于6个连续索引中,其中a [ 0] [1] [n] [5]每隔6个元素,而a [1] [n] [3] [6]每隔5 * 6个元素,依此类推。
但是,指针提供“间接”。 多维数组可以通过first_level数组a [3]实现,该数组提供指向下一级数组b [4],c [4]和d [4]的3个指针(间接),每个指针提供到下一级的间接指示,依此类推。
在许多现实生活中的应用程序(例如,指向字符串的指针表)中,由于语法隐藏了细节,因此确实看不到区别:
int main(int ac, char **av) {
//即使原型可以用int main(int ac, char *av[]);
表示,也可以使用av[2][2]
获得第三个字符串的第三个字符。 int main(int ac, char *av[]);
,但不能使用int main(int ac, char av[][]);
因为表av的大小可能无法通过该语法确定。
问题的根源是C和C ++处理多维数组的方式。 当涉及const
时,问题会放大。
该std::pair<int [3][3], int>
是一对值,其中第二个是int
,第一个是指向int[3]
数组的指针。 由于许多原因,第一个要素是有问题的。 一个是它是一个指针。 另一个是const
确实使多维数组变得奇怪。 那就是你遇到的问题。
您想要的是一个3x3数组作为对象。 所以-使其成为对象:
struct Board {
int arr[3][3];
};
现在您的对变成std::pair<Board,int>
,向量成为std::vector<std::pair<Board, int> >
。 现在您可以安全地从局部变量构造一个Board
, int
对,因为Board
被复制了。 您不能使用原始C多维数组安全地执行此操作,因为第一个元素将是指针。
您的board
定义了一个常量指针。 实际上, int (* const)[3]
与int[n][3]
变量相同:只是一个指向3个整数的数组的指针(尽管第一个是常数1)!
您有三种选择:
int (*const)[3]
board
定义为动态分配的阵列。 (使用int (*board)[3] = new int[3][3];
) board
到一个非const变量。 (最好不要这样做:D) LG ntor
PS:但是,我也建议为此编写一个类并重载[]运算符。 更先进的技术 ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.