【问题标题】:How to find out the size of two dimensional an int array in C++?如何在 C++ 中找出二维 int 数组的大小?
【发布时间】: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 就足够了。无论如何,指针的大小总是一样的。
  • 您有什么理由不能使用vectorboost::multi_array 吗?
  • Chris, Brendan Long:我必须使用双指针,因为这是一个学校项目,并且必须使用双指针。

标签: c++ arrays multidimensional-array sizeof


【解决方案1】:

在 C 或 C++ 中,无法“找到”指针指向的大小。指针只是一个地址值。您必须将大小 - 或者在您的情况下将行数或列数传递给 addTables 函数 - 例如:

int** addTables(int ** table1, int ** table2, int rows, int columns)

这就是评论者建议vector 之类的原因。 C++ 提供比原始指针更好的数据类型 - 一方面,向量跟踪它包含的项目数,因此不必作为单独的参数传递。

在您的示例程序中,sizeof 运算符返回所提供变量类型的大小。所以对于sizeof(tablePtr),它返回int** 的大小,可能是4 或8 个字节。 sizeof 操作是在编译时评估的,因此它无法知道tablePtr 指向的缓冲区有多大。

【讨论】:

  • 不过,将容器与指针进行比较并没有什么意义。在 C 中函数习惯性地接受一对指针或 (pointer, size) 对的情况下,函数可以接受 C++ 中的一对迭代器。 (请记住,一对指针就是一对迭代器。)
  • shf301:好的,谢谢,我想我必须将行和列作为函数参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2020-06-10
  • 1970-01-01
相关资源
最近更新 更多