0

I need to use array in function, but i just get error every time when i run programm.

I tried to make a little render programm, and i was trying to make it using arrays. After many attempts i still cant repair it, can you help me, give some advices like: how can i avoid it, or repair it.

It's not code of programm, it is just example.

#include <iostream>

void func_W(int*arr[])
{
    for(int i = 0; i < 8; i++){
        for(int j = 0; j < 3; j++){
            std::cout << arr[i][j];
            arr[i][j] = 1;
            std::cout << arr[i][j];
        };
    };
};

int main()
{
    int arr1[8][3];
    func_W(arr1);
}
mch
  • 9,424
  • 2
  • 28
  • 42
  • See [Passing a 2D array to a C++ function](https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function) and [Passing Arrays to Function in C++](https://stackoverflow.com/questions/14309136/passing-arrays-to-function-in-c) and [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – Jason Dec 02 '22 at 08:25

1 Answers1

1

Like any other array, arr1 will decay to a pointer to its first element. The problem is that the elements of arr1 are in turn arrays, and those does not decay.

So arr1 will decay to &arr1[0], which has the type int (*)[3]. Which is the type you need for the argument:

void func_W(int (*arr)[3])

Or use std::array instead, which is a wrapper around arrays but with added container-like functionality:

// Define an alias for an 8x3 "2D" array
using array_type = std::array<std::array<int, 3>, 8>;

// ...

void func_W(array_type& arr)
{
    for (auto& inner_arr : arr)
    {
        for (auto& ref : inner_arr)
        {
            ref = 1;
        }
    }
}

int main()
{
    array_type arr1;
    func_W(arr1);
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621