#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++){
cout << troysArray[i] << endl;
cout << troysArray[j] << endl;
};
return 0;
}
当我实际上试图打印出数组的内容时,为什么上面的代码会打印出十六进制数字。 (初学者/只是练习)
我在做错什么导致这种情况发生?
答案 0 :(得分:2)
toString
std::ostream
运算符对<<
的最佳重载为troysArray[i]
(利用指针衰减 ),并输出指针的地址。
如果要使用 元素,请使用void*
&c。
答案 1 :(得分:0)
troysArray[i]
和troysArray[j]
是指向数组的指针。如果要在i
和j
处打印元素,请使用
cout << troysArray[i][j] << endl;
答案 2 :(得分:0)
troysArray
是int
的数组的数组。
因此,troysArray[i]
是int
的数组,troysArray[j]
也是如此。
operator <<
的数组没有int
的重载。
但是,void*
有一个。
将数组作为参数传递时,实际传递的是指向数组第一个元素的指针。
(在您的情况下,它们分别是&troysArray[i][0]
类型的&troysArray[j][0]
和int*
。)
int*
可以隐式转换为void*
,因此可以使用operator <<
的{{1}}。
此重载以十六进制形式输出指针的值。
要打印void*
,您需要打印每个数组int
的元素j
:
troysArray[i]
将其打印得更像“矩阵式”,每一行都位于自己的行上:
cout << troysArray[i][j] << endl;
答案 3 :(得分:0)
将表格的内容打印成网格(如对Guarev Senghai的答案的评论之一所要求的:
#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
{
for (j = 0;j < 3;j++)
{
cout << troysArray[i][j];
//uncomment the next line to have a spaces between the numbers.
cout << " ";
}
cout << endl;
}
return 0;
}