【发布时间】:2012-09-09 04:01:29
【问题描述】:
我在使用涉及二维数组的 C++ 程序时遇到问题。
作为程序的一部分,我必须使用一个函数,该函数接受两个表作为参数并将它们相加,然后返回另一个表。
我想我可以这样做:
int** addTables(int ** table1, int ** table2)
{
int** result;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
result[i][j] = table1[i][j] + table2[i][j];
}
}
return result;
}
但我不知道如何为我的“for”循环找出表格(行和列)的大小。
有人知道怎么做吗?
这是我正在测试的代码的一部分,但我没有得到正确的列数和行数:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(int argc, char **argv)
{
const int n = 3; // In the addTables function I'm not supposed to know n.
int **tablePtr = new int*[n]; // I must use double pointer to int.
for (int i = 0; i < n; i++)
{
tablePtr[i] = new int[n];
}
srand((unsigned)time(0));
int random_integer;
for(int i = 0; i < n; i++) // I assign random numbers to a table.
{
for (int j = 0; j < n; j++)
{
random_integer = (rand()%100)+1;
tablePtr[i][j] = random_integer;
cout << tablePtr[i][j] << endl;
}
}
cout << "The table is " << sizeof(tablePtr) << " columns wide" << endl;
cout << "The table is " << sizeof(tablePtr) << " rows long" << endl;
return 0;
}
感谢您的帮助,请记住我是 C++ 新手。
【问题讨论】:
-
当你说我必须使用指向int的双指针时,这是否意味着约束?如果没有,我肯定会推荐使用向量。当您不需要包装 1D 的额外速度或优雅时,2D 就足够了。无论如何,指针的大小总是一样的。
-
您有什么理由不能使用
vector或boost::multi_array吗? -
Chris, Brendan Long:我必须使用双指针,因为这是一个学校项目,并且必须使用双指针。
标签: c++ arrays multidimensional-array sizeof