c++ - C++ 中接受 2D 数组、将其乘以整数并返回新的 2D 数组的函数?

标签 c++ arrays

假设我有一个包含整数元素的 3x4 数组,我想将此数组传递给一个函数,然后该函数获取所有元素并将它们乘以某个整数“b”,然后返回这个新数组,我将如何处理?这就是我目前拥有的

#include <iostream>
#include <math.h>

using namespace std;

// my function for multiplying arrays by some integer b
int* multarray(int (*a)[4], int b)
{
    for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                *(*(a+i)+j) *= b;
            }
        }
    return *a;
}

int main()
{
    // creating an array to test, values go from 1-12
    int arr [3][4];
    int k = 1;

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            arr[i][j] = k;
            k++;
        }
    }

    // trying to setup new 'array' as a product of the test array
    int *newarray;
    newarray = multarray(arr,3);

    // printing values (works with *(newarray+i) only)
    for (int i = 0; i < 3; i++)
    {
        for (int j=0; j<4; j++)
        {
            cout << *(*(newarray+i)+j);
        }
    }


return 0;
}

如果我在打印所有值时不包含 j 部分,则此方法有效,但现在它告诉我有一个错误:一元 '*' 的类型参数无效(具有 'int')

最佳答案

您的函数没有返回新数组,而是修改现有数组。因此(假设这对您来说不是问题)您应该将返回类型更改为 void。

void multarray(int (*a)[4], int b)
{
    ...
}

然后

multarray(arr,3);
for (int i = 0; i < 3; i++)
{
    for (int j=0; j<4; j++)
    {
        cout << *(*(arr+i)+j);
    }
}

如果您确实想要一个返回新数组的函数,那么这是一个完全不同(而且更复杂)的问题。不说别的,严格来说,在 C++ 中返回数组是不可能的。

关于c++ - C++ 中接受 2D 数组、将其乘以整数并返回新的 2D 数组的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64763717/

相关文章:

c++ - std::vector 和 std::string 重新分配策略

c++ - std::chrono::duration 默认是如何构造的?

带模式或格式的 C scanf

c# - 如何从数组中随机选择一行?

iphone - 在 iPhone sdk 中搜索数组中的值

php - 在 PHP session 中保存数组

python - 拆分数组 'logarithmically' 中的值/基于另一个数组

c++ - 在模板中使用 std::max 时出错

c++ - std::unique_ptr 上的 CPPUNIT_ASSERT_EQUAL

c++ - 有没有办法防止 vector 中的元素被破坏?