c++ - 如何在 C++ 中找出二维 int 数组的大小?

标签 c++ arrays multidimensional-array sizeof

我在处理涉及二维数组的 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/

相关文章:

C++ Template meta-magic, template call-site qualification deduction机制

c++ - 由于私有(private)继承而无法访问迭代器

PHP 在页面加载时随机选择 css 文件

java - 包含所有元素的二维数组的深拷贝

c++ - 从变量初始化数组 (C++)

c++ - 为什么我的代码出现段错误

c++ - 为什么采用 std::initializer_list 的构造函数不首选双花括号语法

java - java中x数据类型数组占用的实际大小(以字节为单位)?

C++简单文件读入数组问题

PHP 返回匹配键名和值的数组