我是c++新手,我正在学习如何使用指针和数组。我很难处理一段正在编译的代码,并且似乎在做它应该做的事情,除了主函数中指针的输出似乎是一个内存地址外,所以我在调用或返回指针的方式上肯定遗漏了一些东西。(我希望我的术语是正确的)
在我的主函数中,我创建了一个指针变量并将其初始化为null (教授建议初始化所有的vars)。
int** ptr1=NULL;接下来,我将指针设置为我的函数,该函数创建数组。
ptr1 = makeArray1();这是我的函数的代码。
int** makeArray1(){
const int ROW = 2;
const int COL = 3;
int** array1 = new int* [ROW]; //This creates the first row of cols
for (int i = 0; i < ROW; i++)
{
array1[i] = new int[COL]; //loop to create next col of all rows
}
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
cout << endl << "Please enter an integer in the first matrix: ";
cin >> array1[i][j];
}
}
cout << endl;
for (int i = 0; i < ROW;i++)
{
for (int j = 0; j < COL; j++)
{
cout << setw(4) << array1[i][j];
}
cout << endl;
}
cout << endl << endl << "In array 2 array2 = " << *array1;
return array1;}
数组似乎填充了我的输入,但是当我在主函数中打印ptr1时,它返回一个内存地址,而不是输入到数组中的数字。
任何帮助都将不胜感激。
发布于 2015-10-03 05:02:17
打印指针将打印指针的值。这是一个内存地址。如果希望在2d数组的开头看到值,则需要取消对指针的引用。
发布于 2015-10-03 04:59:33
尝试声明: int** array1 = new * ROW;如果可以的话,请在函数外部声明
发布于 2015-10-03 05:04:18
ptr1是一个指针。难怪你得到了一个内存入口,因为指针就是一个内存入口。如果要打印数组的内容,则必须取消对指针的引用。就像这样:
for(int i=0; i < ROW; i++) {
for(int j=0; j < COL; j++) {
cout<<ptr1[i][j];
}
}https://stackoverflow.com/questions/32919053
复制相似问题