How to Pass a Reference to a Two-Dimensional Array to a Function

Passing a 2D array to a C++ function

There are three ways to pass a 2D array to a function:

  1. The parameter is a 2D array

    int array[10][10];
    void passFunc(int a[][10])
    {
    // ...
    }
    passFunc(array);
  2. The parameter is an array containing pointers

    int *array[10];
    for(int i = 0; i < 10; i++)
    array[i] = new int[10];
    void passFunc(int *a[10]) //Array containing pointers
    {
    // ...
    }
    passFunc(array);
  3. The parameter is a pointer to a pointer

    int **array;
    array = new int *[10];
    for(int i = 0; i <10; i++)
    array[i] = new int[10];
    void passFunc(int **a)
    {
    // ...
    }
    passFunc(array);

Passing 2D array by reference to function

The problem is that the methods:

void input(int*, int*);
void add(int*, int*, int*);
void display(int*);

expected a pointer, however you are passing to them 2D arrays (statically allocated), namely int a[3][3], b[3][3], sum[3][3];. Therefore, as already pointed out in the comments, those 2D arrays will be converted to 'int (*)[3]'. Consequently, you need to adapt the signature of your methods to:

void input(int [][3], int [][3]);
void add(int [][3], int [][3], int [][3]);
void display(int [][3]);

and

void input(int a[][3], int b[][3]){
// the code
}

void add(int a [][3], int b [][3], int sum [][3]){
// the code
}

void display(int sum [][3]){
// the code
}

Alternatively, if you want to keep the int* as parameter then what you can do is to allocate the matrix as a single array and adapt your code accordingly

How to pass a 2D array by pointer in C?

char ** doesn't represent a 2D array - it would be an array of pointers to pointers. You need to change the definition of printarray if you want to pass it a 2D array:

void printarray( char (*array)[50], int SIZE )

or equivalently:

void printarray( char array[][50], int SIZE )

Why isn't it possible to pass a two-dimensional array as function argument?

What he does mean when he says "const pointer to static array"?

I think he meant to say that the array needs to be treated as though it's contiguous; it needs to be a sequence of elements one after the other with no room for pointers. He might be trying to claim that dereferencing a two-dimensional array once (e.g. *mat or mat[0]) should result in a constant that points at the sub-array (which is also incorrect in certain situations, one of which I'll cover soon, when used as the operand of sizeof).

FWIW, this is also incorrect:

The previous header would be correct if the matrix is dynamic array.

int mat[SIZE][SIZE]; If we inspect this object, sizeof mat is equal to sizeof (int) * SIZE * SIZE; there's no room for any pointer storage within this matrix. However, in void ins (int **matrix, int row, int column);, int **matrix tells us that matrix points at int *, which implies that there is room for pointers, and also implies that matrix might not be contiguous.

... how this is coded?

Incorrectly, for that question, as int ** points at int * objects, not at int[SIZE] objects.

... why it does have to be const pointer to a static array?

See the first paragraph of this answer.

How to pass a 2D array by Reference to a function in C++

Since you already use vector<vector<char>>& board as one parameter, the simplest way to fix this error is to use vector<vector<int>> b1 instead of int b1[m][n].

Please take care of VLAs like int a[n][m], it's not easy to maintain and also not recommended. See more at Why aren't variable-length arrays part of the C++ standard?.

Here is my example to replace your b1 with a 2D vector.

class Solution {
public:

bool exist(vector<vector<char>> &board, string word) {
int m = board.size();
int n = board[0].size();
// int b1[m][n];
vector<vector<int>> b1(m, vector<int>(n, 0));

list<pair<int, int>> mp;

bool yellow = false;
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] == word[0]) {
mp.push_front({i, j});
}
}
}

for (auto itr = mp.begin(); itr != mp.end(); itr++) {
int i = itr->first;
int j = itr->second;

dfs(i, j, board, word, 0, yellow, b1);
if (yellow == true) {

return yellow;
}

// memset(b1, 0, sizeof(b1));
for (auto &row: b1) {
std::fill(row.begin(), row.end(), 0);
}
}
return yellow;
}

// void dfs(int i,int j,vector<vector<char>>& board,string word,int k,bool& yellow,int& b1[][]){
void dfs(int i, int j, vector<vector<char>> &board, string word, int k, bool &yellow, vector<vector<int>> &b1) {
int m = board.size() - 1;
int n = board[0].size() - 1;
b1[i][j] = 1;
if (k == word.size() - 1) {
yellow = true;
}

if (i + 1 <= m && board[i + 1][j] == word[k + 1] && b1[i + 1][j] == 0) {
dfs(i + 1, j, board, word, k + 1, yellow, b1);
}
if (i - 1 >= 0 && board[i - 1][j] == word[k + 1] && b1[i - 1][j] == 0) {
dfs(i - 1, j, board, word, k + 1, yellow, b1);
}
if (j + 1 <= n && board[i][j + 1] == word[k + 1] && b1[i][j + 1] == 0) {
dfs(i, j + 1, board, word, k + 1, yellow, b1);
}
if (j - 1 >= 0 && board[i][j - 1] == word[k + 1] && b1[i][j - 1] == 0) {
dfs(i, j - 1, board, word, k + 1, yellow, b1);
}
}

};

How to pass 2D array (matrix) in a function in C?

C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:

#define ROWS 4
#define COLS 5

void func(int array[ROWS][COLS])
{
int i, j;

for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
array[i][j] = i*j;
}
}
}

void func_vla(int rows, int cols, int array[rows][cols])
{
int i, j;

for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}

int main()
{
int x[ROWS][COLS];

func(x);
func_vla(ROWS, COLS, x);
}

2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.

void func(int** array, int rows, int cols)
{
int i, j;

for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}

int main()
{
int rows, cols, i;
int **x;

/* obtain values for rows & cols */

/* allocate the array */
x = malloc(rows * sizeof *x);
for (i=0; i<rows; i++)
{
x[i] = malloc(cols * sizeof *x[i]);
}

/* use the array */
func(x, rows, cols);

/* deallocate the array */
for (i=0; i<rows; i++)
{
free(x[i]);
}
free(x);
}

3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:

void func(int* array, int rows, int cols)
{
int i, j;

for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i*cols+j]=i*j;
}
}
}

int main()
{
int rows, cols;
int *x;

/* obtain values for rows & cols */

/* allocate the array */
x = malloc(rows * cols * sizeof *x);

/* use the array */
func(x, rows, cols);

/* deallocate the array */
free(x);
}

4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

extern void func_vla(int rows, int cols, int array[rows][cols]);
extern void get_rows_cols(int *rows, int *cols);
extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);

void func_vla(int rows, int cols, int array[rows][cols])
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = (i + 1) * (j + 1);
}
}
}

int main(void)
{
int rows, cols;

get_rows_cols(&rows, &cols);

int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
/* error check omitted */

func_vla(rows, cols, array);
dump_array("After initialization", rows, cols, array);

free(array);
return 0;
}

void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
{
printf("%s (%dx%d):\n", tag, rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
printf("%4d", array[i][j]);
putchar('\n');
}
}

void get_rows_cols(int *rows, int *cols)
{
srand(time(0)); // Only acceptable because it is called once
*rows = 5 + rand() % 10;
*cols = 3 + rand() % 12;
}

(See srand() — why call it only once?.)

Passing Dynamic Two Dimensional Array as argument to a functoin in c++

you need to get the parameter in your function as pointer

void displayArray(int **a)
{
for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
cout<< a[i][j] <<"\t";
}
cout<<endl;
}
}

int main()
{
int** a = new int*[10];
for(int i = 0; i < 10; ++i)
a[i] = new int[10];

displayArray(a);
}

it prints 10 rows and columns of value 0 because the 2D array is uninitialized



Related Topics



Leave a reply



Submit