简体   繁体   中英

Function that accepts a 2D array, multiplies it by an integer, and returns the new 2D array in C++?

say I have a 3x4 array with integer elements, I want to pass this array to a function that then takes all of the elements and multiplies them by some integer 'b' then returns this new array, how would I go about it? this is what I have currently

#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;
}

this works if I don't include the j part when printing all my values but as it is now, tells me I have an error: invalid type argument of unary '*' (have 'int')

Your function is not returning a new array, it's modifying an existing array. So (assuming this is not a problem for you) you should just change the return type to void.

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

Then

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

If you really do want a function that returns a new array, then that's a whole different (and much more complicated) problem . Apart from anything else it's, strictly speaking, impossible to return an array in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM