我在处理涉及二维数组的 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++ 的新手。
最佳答案
在 C 或 C++ 中无法“找到”指针指向的大小。指针只是一个地址值。您必须将大小 - 或者在您的情况下将行数或列数传递到 addTables
函数中 - 如:
int** addTables(int ** table1, int ** table2, int rows, int columns)
这就是为什么评论者建议使用 vector
之类的东西。 C++ 提供了比原始指针更好的数据类型 - 一方面, vector 会跟踪它包含的项数,因此它不必作为单独的参数传递。
在您的示例程序中,sizeof
运算符返回所提供变量类型的大小。因此,对于 sizeof(tablePtr)
,它返回 int**
的大小,这可能是 4 或 8 个字节。 sizeof
操作是在编译时评估的,因此它无法知道 tablePtr
指向的缓冲区有多大。
关于c++ - 如何在 C++ 中找出二维 int 数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12336419/